Tkinter使用checkbutton禁用多个Entry

时间:2013-02-26 21:45:49

标签: python checkbox tkinter tkinter-entry

使用Python 2.7,我想将“Entry”小部件的状态变为正常/禁用感谢一个检查按钮。

借助此问题Disable widget with checkbutton?,我可以使用1个checkbutton和1个条目

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import Tkinter as tk

root = tk.Tk()


class Principal(tk.Tk):
    def __init__(self, *args, **kwargs):
        self.foo = tk.StringVar()
        self.nac = tk.IntVar()

        self.ck1 = tk.Checkbutton(root, text='test',
            variable=self.nac, command=self.naccheck)
        self.ck1.pack()

        self.ent1 = tk.Entry(root, width=20, background='white',
            textvariable=self.foo, state='disabled')
        self.ent1.pack()

    def naccheck(self):
        print "check"
        if self.nac.get() == 0:
            self.ent1.configure(state='disabled')
        else:
            self.ent1.configure(state='normal')

app = Principal()
root.mainloop()

当我想要2对或更多对(问题按钮/条目)时出现问题。 在我的最终界面中,我可能有20个或更多这一对,所以我想避免使用20个或更多相同的“naccheck”方法。

我试过了:

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

import Tkinter as tk

root = tk.Tk()


class Principal(tk.Tk):
    def __init__(self, *args, **kwargs):
        self.foo = tk.StringVar()
        self.nac = {}
        self.ent = {}

        self.ent["test"] = tk.Entry(root, width=20, background='white', textvariable=self.foo, state='disabled')
        self.ent["test"].pack()

        self.ent["image"] = tk.Entry(root, width=20, background='white', textvariable=self.foo, state='disabled')
        self.ent["image"].pack()

        self.nac["test"] = tk.IntVar()
        self.ck1 = tk.Checkbutton(root, text='test', variable=self.nac["test"], command=self.naccheck("test"))
        self.ck1.pack()

        self.nac["image"] = tk.IntVar()
        self.ck1 = tk.Checkbutton(root, text='image', variable=self.nac["image"], command=self.naccheck("image"))
        self.ck1.pack()


    def naccheck(self,item):
        print "check "+item
        print self.nac[item].get()
        if self.nac[item].get() == 0:
            self.ent[item].configure(state='disabled')
        else:
            self.ent[item].configure(state='normal')

app = Principal()
root.mainloop()

不幸的是,当我启动此代码时,会立即为每个检查按钮调用“naccheck”方法,而且在我点击一个按钮之后永远不会调用...

我做错了什么?

1 个答案:

答案 0 :(得分:7)

有很多方法可以解决这个问题。一种方法是将entry和checkbutton变量传递给check函数。首先创建条目小部件和变量。然后,创建checkbutton并将变量和条目传入回调函数:

ent = tk.Entry(...)
var = tk.IntVar()
chk = tk.Checkbutton(..., command=lambda e=ent, v=var: self.naccheck(e,v))

注意lambda的使用,这是一种创建匿名函数的简单技术。这使您可以将参数传递给回调,而无需创建命名函数。另一种选择是使用functools.partial。毫无疑问,StackOverflow上有很多例子,因为这是一个非常常见的问题。

接下来,您需要修改函数以接受参数:

def naccheck(self, entry, var):
    if var.get() == 0:
        entry.configure(state='disabled')
    else:
        entry.configure(state='normal')
相关问题