网络编程
位置:首页>> 网络编程>> Python编程>> tkinter如何获取复选框(Checkbutton)的值

tkinter如何获取复选框(Checkbutton)的值

作者:乌拉队长  发布时间:2023-10-01 22:41:35 

标签:tkinter,复选框,Checkbutton

tkinter获取复选框(Checkbutton)的值

定义GUI:

from tkinter import *

# 初始化Tk()
myWindow = Tk()
# 设置标题
myWindow.title('Python GUI Learning')
myWindow.geometry("%dx%d+%d+%d"%(400, 200, 200, 200))
# 创建Checkbutton
checkVar = StringVar(value="0")
check = Checkbutton(myWindow, text="Checkbutton test", variable=checkVar)
check.grid(row=0, column=0, sticky=W, padx=2 ,pady=5)
# 定义按钮点击事件
def button_Click(event=None):
   print(checkVar.get())

# 创建两个按钮
b1 =Button(myWindow, text='click me' , relief='raised', width=8, height=1, command=button_Click)
b1.grid(row=0, column=2, sticky=W, padx=2 ,pady=10)

# 进入消息循环
myWindow.mainloop()

效果:

tkinter如何获取复选框(Checkbutton)的值

对复选框进行操作后,点击按钮输出信息:

tkinter如何获取复选框(Checkbutton)的值

tkinter包的使用-Checkbutton

下面的例子讲一下如何使用Checkbutton,它和Radiobutton的区别是,Radiobutton只可以选中一个,是单选按钮,Checkbutton可以同时选中多个,是多选按钮。

tkinter如何获取复选框(Checkbutton)的值

只选中Python:

tkinter如何获取复选框(Checkbutton)的值

只选中C++:

tkinter如何获取复选框(Checkbutton)的值

两个都选中:

tkinter如何获取复选框(Checkbutton)的值

都不选:

tkinter如何获取复选框(Checkbutton)的值

代码:

import tkinter as tk

window=tk.Tk()
window.title('my window')
window.geometry('200x100')

l=tk.Label(window,
          bg='yellow',
          width=20,
          text='empty')
l.pack()

def print_selection():
   if(var1.get()==1)&(var2.get()==0):
       l.config(text='I love only Python ')
   elif (var1.get()==0)& (var2.get()==1):
       l.config(text='I love only C++')
   elif (var1.get()==0)&(var2.get()==0):
        l.config(text='I do not love either')
   else:
       l.config(text='I love both')

var1=tk.IntVar()
var2=tk.IntVar()
c1=tk.Checkbutton(window,
                 text='Python',
                 variable=var1,
                 onvalue=1,
                 offvalue=0,
                 command=print_selection
                 )
c1.pack()
c2=tk.Checkbutton(window,
                 text='C++',
                 variable=var2,
                 onvalue=1,
                 offvalue=0,
                 command=print_selection
                 )
c2.pack()

window.mainloop()

在Checkbutton()中参数onvalue和前面讲的部件radiobutton中的value相似, 当我们选中了这个checkbutton,onvalue的值1就会放入到var1中, 然后var1将其赋值给参数variableoffvalue用法相似,但是offvalue是在没有选中这个checkbutton时,offvalue的值1放入var1,然后赋值给参数variable 这是创建一个checkbutton部件,以此类推,可以创建多个checkbutton

在print_selection()中config在之前的例子中就是将参数text的值显示,这里的var1.get() == 1 就是前面所说的var1获得的变量onvalue=1var1.get() == 0即是var1获得的变量offvalu=0同理var2也是如此。

来源:https://blog.csdn.net/asdfg6541/article/details/103971788

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com