如何在Tkinter中获取多个Checkbutton的状态? [英] How to get the state of multiple Checkbuttons in Tkinter?

查看:509
本文介绍了如何在Tkinter中获取多个Checkbutton的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小的Tkinter / Python程序,其中包含具有可变长度(在运行时确定)的复选框列表。

I am writing a small Tkinter/Python program, that has a list of checkboxes with variable length (determined at run time).

我希望能够随时读取所有复选框的状态,但是我不确定该怎么做。

I want to be able to read the state of all the checkboxes at any time, but I am not sure how I should go about that.

以下是用于生成列表的代码段(从此帖子):

Here's the code snippet for generating the list (adopted from this post):

def relist(self):
    self.text.delete(1.0,END)
    p = subprocess.Popen (['ls', '/dev/'], stdout = subprocess.PIPE)
    lst = p.communicate()[0].split('\n')
    print lst
    for item in lst:
        v = tk.IntVar()
        cb = tk.Checkbutton(text="/dev/%s" % item, variable=v, command=self.cb(index))
        self.text.window_create("end", window=cb)
        self.text.insert("end", "\n") # to force one checkbox per line

虚拟处理程序:

def cb(self,idx):
    print ("var is %s", str(idx))
    lst[idx] = 1;

问题是我的处理程序被调用一次(创建Checkbuttons时),而我想要每次单击(选中或取消选中) Checkbutton 时都会调用它,并且在调用它时,我希望它更新一次。

The problem is that my handler is getting called once (when the Checkbuttons are created), whereas I want it to get called everytime a Checkbutton is clicked (checked or unchecked), and when it is called, I want it to update lst.

推荐答案

您的CheckButton命令正在执行回调,因为这就是您要告诉它执行的操作。该命令应该是对单击tkinter时可以执行的功能的引用。 Tkinter将事件对象传递给回调函数。请参阅此 Effbot 教程,但是您似乎已经在尝试实现其模式了。您可以在此处。最后,如果要在回调中引用变量,则需要将变量附加到 self。

Your CheckButton command is executing the callback because that's what you are telling it to do. The command is supposed to be a reference to a function that tkinter can execute when the checkbutton is clicked. Tkinter passes the event object to the callback function. See this Effbot tutorial, but it looks like you are trying to implement their pattern already. You can get a reference to the checkbutton from the event.widget attribute as explained here. Finally, you need to attach your variable to "self" if you want to refer to it in the callback.

def relist(self):
    self.text.delete(1.0,END)       
    p = subprocess.Popen (['ls', '/dev/'], stdout = subprocess.PIPE)       
    lst = p.communicate()[0].split('\n')       
    print lst       
    self.var = tk.IntVar()
    for item in lst:           
        cb = tk.Checkbutton(text="/dev/%s" % item, variable=self.var, command=self.myCallback)
        self.text.window_create("end", window=cb)     
        self.text.insert("end", "\n") # to force one checkbox per line

def myCallback(self,event):
    var = self.var.get()
    print ("var is %s", str(var))

这篇关于如何在Tkinter中获取多个Checkbutton的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆