Tkinter使用checkbutton禁用多个Entry

eri*_*icc 2 python checkbox tkinter tkinter-entry

使用Python 2.7,我想将"Entry"小部件的状态转换为正常/禁用感谢一个checkbutton.

在这个问题的帮助下,使用checkbutton禁用小部件?,我可以用1个checkbutton和1个Entry进行

#!/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()
Run Code Online (Sandbox Code Playgroud)

当我想要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()
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我启动这个代码时,立即为每个checkbutton调用方法"naccheck",并且在我点击一个后立即调用...

我做错了什么?

Bry*_*ley 7

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

ent = tk.Entry(...)
var = tk.IntVar()
chk = tk.Checkbutton(..., command=lambda e=ent, v=var: self.naccheck(e,v))
Run Code Online (Sandbox Code Playgroud)

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

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

def naccheck(self, entry, var):
    if var.get() == 0:
        entry.configure(state='disabled')
    else:
        entry.configure(state='normal')
Run Code Online (Sandbox Code Playgroud)