Tkinter นำเสนอคุณลักษณะสำหรับการเพิ่มวิดเจ็ตประเภทต่างๆ ที่จำเป็นสำหรับแอปพลิเคชัน วิดเจ็ตเหล่านี้บางส่วน ได้แก่ วิดเจ็ตปุ่ม วิดเจ็ตรายการ กล่องข้อความ ตัวเลื่อน ฯลฯ ในบทความนี้ เราจะมาดูกันว่าเราจะสร้างแอปพลิเคชันโดยใช้ปุ่มที่สามารถเปิดหรือปิดได้อย่างไร
ในตัวอย่างนี้ เราจะใช้สองปุ่มนี้ในการสาธิต
-
เปิดเครื่อง
-
ปิดสวิตช์
ตัวอย่าง
# Import tkinter in the notebook
from tkinter import *
# Create an instance of window of frame
win =Tk()
# set Title
win.title('On/Off Demonstration')
# Set the Geometry
win.geometry("600x400")
win.resizable(0,0)
#Create a variable to turn on the button initially
is_on = True
# Create Label to display the message
label = Label(win,text = "Night Mode is On",bg= "white",fg ="black",font =("Poppins bold", 22))
label.pack(pady = 20)
# Define our switch function
def button_mode():
global is_on
#Determine it is on or off
if is_on:
on_.config(image=off)
label.config(text ="Day Mode is On",bg ="white", fg= "black")
is_on = False
else:
on_.config(image = on)
label.config(text ="Night Mode is On", fg="black")
is_on = True
# Define Our Images
on = PhotoImage(file ="on.png")
off = PhotoImage(file ="off.png")
# Create A Button
on_= Button(win,image =on,bd =0,command = button_mode)
on_.pack(pady = 50)
#Keep Running the window
win.mainloop() ผลลัพธ์
การเรียกใช้โค้ดด้านบนจะสร้างปุ่มสำหรับเปิด/ปิดโหมด

หากคุณคลิกที่ปุ่ม มันจะเปลี่ยนไปดังนี้ −
