如何建立一個 Tkinter 開關按鈕?
Python 擁有豐富且功能齊全的庫和模組,可用來構建應用程式的各種元件。Tkinter 是另一個用於建立和開發基於 GUI 的應用程式的著名 Python 庫。Tkinter 提供了許多小元件、函式和模組,用於為應用程式的視覺化效果增添生機。我們可以建立按鈕小元件來執行應用程式中的某些任務。
在此應用程式中,我們將建立一個切換按鈕,該按鈕將開啟或關閉應用程式的夜間和白天模式。要建立一個切換按鈕,我們必須先在標籤中渲染影像。
我們定義按鈕和函式來更改視窗的背景顏色。由於這些按鈕需要反覆更改,所以我們必須宣告一個全域性變數 is_on=True,此變數有助於控制函式。
示例
# Import tkinter in the notebook
from tkinter import *
# Create an instance of window of frame
win = Tk()
# set Title
win.title('Toggle Button Demonstration')
# Set the Geometry
win.geometry("700x400")
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()輸出
如果執行上述程式碼,將顯示一個包含有切換按鈕的視窗。
如果單擊按鈕,它將更改視窗的顏色。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP