Python-tkinter6:一个简单的tkinter(checkbutton 勾选项)
Python-tkinter6:一个简单的tkinter(checkbutton 勾选项)
示例代码:
import tkinter as tk
# 1.创建窗口
window = tk.Tk()
# 2.设置窗口属性
window.geometry("200x400")
window.title('my-window')
# 3.设置组件
# 3.1 label 标签
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
#
def print_selection():
if (c1_var.get() == 1) & (c2_var.get() == 1):
l.config(text='I love both!')
elif (c1_var.get() == 1) & (c2_var.get() == 0):
l.config(text='I love Python!')
elif (c1_var.get()==0) & (c2_var.get()==1):
l.config(text="I love C++")
else:
l.config(text="I dont love neither!")
# 3.2 checkbutton 勾选项
c1_var = tk.IntVar() # 用的tkinter自己的变量类型
c2_var = tk.IntVar() # 用的tkinter自己的变量类型
# 参数:variable:绑定的变量
# 当选中时,就把onvalue的值赋给variable绑定的变量(此处就是把1赋给c1_var)
# 当不选中时,就把offvalue的值赋给variable绑定的变量(此处及时把0赋给c1_var)
# command:触发想要执行的函数
c1 = tk.Checkbutton(window, text="Python", variable=c1_var, onvalue=1, offvalue=0, command=print_selection)
c2 = tk.Checkbutton(window, text='C++', variable=c2_var, onvalue=1, offvalue=0, command=print_selection)
c1.pack()
c2.pack()
# 4.运行窗口
window.mainloop()
效果:
Python-tkinter6:一个简单的tkinter(checkbutton 勾选项)相关教程