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()输出
运行上述代码将创建一个用于操作开/关模式的按钮。

如果单击该按钮,它将如下更改 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP