0

我刚刚开始学习将 tkinter 与 python 一起使用,这种尝试使用简单的脚本来打印输入框中输入的任何内容似乎是违反直觉的,但不起作用:

class App:
    def __init__(self, master):

        frame  = Frame(master)
        frame.pack()

        text_write = Entry(frame)
        text_write.pack()

        self.button = Button(frame, text="quit", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text='hello', fg='black', command=self.say_hi(text_write.get()))
        self.hi_there.pack(side=RIGHT)

    def say_hi(self, text):
        print(text)

root = Tk()

app = App(root)

root.mainloop()

这什么也不做,也不输出任何错误,但如果我把它改成这样:

class App:
    def __init__(self, master):

        frame  = Frame(master)
        frame.pack()

        self.text_write = Entry(frame)
        self.text_write.pack()

        self.button = Button(frame, text="quit", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text='hello', fg='black', command=self.say_hi)
        self.hi_there.pack(side=RIGHT)

    def say_hi(self):
        print(self.text_write.get())

然后它调用函数并打印值。为什么需要在此处声明“自我”?为什么不能将 text_write 的值作为参数传递给 say_hi(如第一个示例所示)并显示?或者你和我只是做错了吗?

4

1 回答 1

0

当你这样做时:

self.button = Button(..., command=func())

然后 python 将调用func(),其结果将分配给 command 属性。由于您的 func 不返回任何内容,因此命令将为无。这就是为什么当你按下按钮时,什么也没有发生。

你的第二个版本看起来不错。需要的原因self是没有它,text_write是一个仅对 init 函数可见的局部变量。通过使用self,它成为对象的属性,因此对象的所有方法都可以访问。

如果您想学习如何传递与第一次尝试类似的参数,请在此站点中搜索lambdaand的用法functools.partial。此类问题已被多次询问和回答。

于 2013-01-17T12:27:22.423 回答