ในตัวอย่างนี้ เราจะสร้างปุ่มโค้งมนในหน้าต่างที่สามารถใช้ได้ในแอปพลิเคชันอื่นๆ มากมาย เช่น แบบฟอร์ม เกม กล่องโต้ตอบ ฯลฯ
วิธีที่ดีที่สุดในการสร้างปุ่มโค้งมนใน Tkinter คือการใช้รูปภาพของปุ่มที่ต้องการและเปลี่ยนเป็นปุ่มที่คลิกได้ในเฟรม เป็นไปได้จริง ๆ โดยใช้ PhotoImage() ฟังก์ชันที่จับภาพที่ต้องการของปุ่ม
ดังนั้น ขั้นตอนต่อไปนี้จะทำให้ภาพที่ต้องการเป็นปุ่ม
-
ขั้นแรก เราจะสร้างปุ่มจำลองที่สามารถใช้เพื่อทำให้ภาพคลิกได้
-
หยิบภาพจากแหล่งที่มาโดยใช้ฟังก์ชัน PhotoImage(ไฟล์)
-
ส่งไฟล์รูปภาพเป็นค่าในฟังก์ชันปุ่ม
-
ลบ 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() ผลลัพธ์
การรันโค้ดด้านบนจะสร้างผลลัพธ์ต่อไปนี้ -
