将Python对象作为参数传递给tkinter的条目validatecommand

2024-05-15 15:11:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Tkinter的“validatecommand”函数来验证输入框中的输入。我希望传递我的类对象,以便验证函数可以从该对象请求信息。然而,validatecommand函数似乎将我传递的所有内容都转换为字符串。因此,验证函数现在具有__main__.foo object at 0x042981B0但为字符串。我如何传递原始的__main__.foo? 它当前看起来像这样(伪代码):

class foo(object):
    def start(program):
        self.stuff = 5 #stuff changes while the program is running
        tkinter_stuff(program)
def tkinter_stuff(program):
    Entry = tkinter.Entry(validatecommand = (window.register(validate_entry), '%P', program))
def validate_entry(entry, program): #checks if current stuff + the amount of staff that would be added over this entry box is <= 20
    if int(entry) + program.get_stuff() <= 20:
        return True
    return False
program = foo() #there are other classes that create their own program and overwrite the one the entry uses, so I can't rely on this one
program.start(program)

实际代码:

import tkinter
class foo(object):
    def __init__(self):
        self.stuff = 5 #stuff changes while the program is running
    def start(self, program):
        tkinter_stuff(program)
    def get_stuff(self):
        return self.stuff
def tkinter_stuff(program):
    window = tkinter.Tk(className = 'window')
    window.geometry('50x50')
    print(program, type(program))
    Entry = tkinter.Entry(window, width = 10, validate = 'key', validatecommand = (window.register(validate_entry), '%P', program))
    Entry.place(x = 10, y = 10)
    window.update()
def validate_entry(entry, program): #checks if current stuff + the amount of staff that would be added over this entry box is <= 20
    print(program, type(program))
    if int(entry) + program.get_stuff() <= 20:
        return True
    return False
program = foo() #there are other classes that create their own program and overwrite the one the entry uses, so I can't rely on this one
program.start(program)

Tags: the函数selfreturnfootkinterdefwindow
1条回答
网友
1楼 · 发布于 2024-05-15 15:11:48

试试这个:

import tkinter as tk


class Entry(tk.Entry):
    def __init__(self, master=None, args=tuple(), validatecommand=None, **kwargs):
        if validatecommand is not None:
            self.args = args
            self.callers_function = validatecommand[0]
            validatecommand = (root.register(self.validatecommand), *validatecommand[1:])
        super().__init__(master, validatecommand=validatecommand, **kwargs)

    def validatecommand(self, *args):
        return self.callers_function(*args, *self.args)


class Foo:
    def __init__(self):
        pass


def validate_entry(entry, program):
    print(type(entry), type(program))
    return True


program = Foo()

root = tk.Tk()

# Make sure it's not `root.register(validate_entry)`:
entry = Entry(root, validate="key", validatecommand=(validate_entry, "%P"),
              args=(program, ))
entry.pack()

root.mainloop()

我刚刚创建了一个包装类,它将使用创建Entry时指定的args调用validatecommand

相关问题 更多 >