ในตัวอย่างนี้ เราจะสร้างปุ่มโค้งมน (rounded button) ในหน้าต่าง ที่สามารถนำไปใช้ในแอปพลิเคชันอื่นๆ เช่น ฟอร์ม เกม กล่องโต้ตอบ เป็นต้น
วิธีที่ดีที่สุดในการสร้างปุ่มโค้งมนใน Tkinter คือใช้รูปภาพปุ่มที่ต้องการและทำให้มันเป็นปุ่มที่คลิกได้ในเฟรม ซึ่งเป็นไปได้ด้วยฟังก์ชัน PhotoImage() ที่จะดึงรูปภาพปุ่มที่ต้องการ
ขั้นตอนต่อไปนี้ทำให้รูปภาพที่ต้องการกลายเป็นปุ่ม:
ก่อนอื่น สร้าง Dummy button ที่ใช้ทำให้รูปภาพคลิกได้
ดึงรูปภาพจากแหล่งที่มาโดยใช้ฟังก์ชัน PhotoImage(file)
ส่งไฟล์รูปภาพเป็นค่าในฟังก์ชัน Button
กำหนด borderwidth=0
ตอนนี้เราได้ปุ่มโค้งมนแล้ว
สำหรับตัวอย่างนี้ เราจะใช้รูปภาพนี้และทำให้มันคลิกได้
ตัวอย่าง
# Import all the necessary libraries
from tkinter import *
# Define the tkinter instance
win = Toplevel()
win.title("Rounded Button")
# Define the size of the tkinter frame
win.geometry("700x300")
# Define the working of the button
def my_command():
text.config(text="You have clicked Me...")
# Import the image using PhotoImage function
click_btn = PhotoImage(file='clickme.png')
# Let us create a label for button event
img_label = Label(image=click_btn)
# Let us create a dummy button and pass the image
button = Button(win, image=click_btn, command=my_command, borderwidth=0)
button.pack(pady=30)
text = Label(win, text="")
text.pack(pady=30)
win.mainloop()
ผลลัพธ์
การรันโค้ดข้างต้นจะให้ผลลัพธ์ดังนี้:
