Tkinter 中的開/關切換按鈕


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()

輸出

執行上述程式碼將建立一個用於操作開/關模式的按鈕。

如果單擊該按鈕,它將如下更改 −

更新時間:2021-03-06

3000+ 檢視次數

啟動您的 職業生涯

完成課程以獲取認證

開始學習
廣告