Tkinter中的函数

0 投票
1 回答
1261 浏览
提问于 2025-04-17 21:23

我正在用Python练习Tkinter,想学习一些基础知识。现在我的代码是

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.prompt = tk.Label(self, text="Press a button", anchor="w")
        self.button1 = tk.Button(self, text="Button 1", command = self.button1)
        self.button2 = tk.Button(self, text="Button 2", command = self.button2)
        self.output = tk.Label(self, text="")

        # lay the widgets out on the screen. 
        self.prompt.pack(side="top", fill="x")
        self.output.pack(side="top", fill="x", expand=True)
        self.button1.pack(side="left")
        self.button2.pack(side="right")

    def button1(self):
        result = "You just pressed button 1."
        self.output.configure(text=result)
    def button2(self):
        result = "You just pressed button 2."
        self.output.configure(text=result)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

这个代码运行得很好,但我想让它更简洁,只用一个函数。我试着这样做:

def button(self, string):
    result = string
    self.output.configure(text=result)

在按钮上,我使用了

self.button1 = tk.Button(self, text="Button 1", command = self.button(
"You just pressed button 1"))
self.button2 = tk.Button(self, text="Button 2", command = self.button(
"You just pressed button 2"))

不过奇怪的是,当我给按钮的函数添加第二个参数时,它就不工作了。如果我用完全相同的代码,它是可以正常工作的,但一加第二个参数就出现了这个错误:

line 31, in button
    self.output.configure(text=result)
AttributeError: Example instance has no attribute 'output'

那是什么问题呢?

1 个回答

1

问题在于,command 属性需要一个函数的引用。也就是说,当你写 command=self.button(...) 时,其实是立即调用了这个函数,然后把函数的结果作为 command 属性的值。

如果你想传递参数,就需要用到 lambda 或者 functools.partial。这个问题在这个网站上已经被问过很多次了。比如,你可以看看这个链接:在 "command" 和 "bind" 中调用带参数的函数 以及 python Tkinter: 向函数传递参数

撰写回答