Tkinter中的功能 [英] Functions in Tkinter

查看:94
本文介绍了Tkinter中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试将Tkinter与python结合使用,而我只是想学习基础知识.我现在的代码是

So I am practicing using Tkinter with python, and I am just trying to learn the basics. My code right now is

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()

这很好用,但是我试图使其更整洁并且仅使用一个功能.我试过了:

This works fine, but I am trying to make it a little cleaner and only use one function. I tried this:

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"))

但是由于某种原因,当我将第二个参数添加到按钮函数时,它停止工作.如果我使用完全相同的代码,则可以正常工作,但是当我添加第二个参数时,会出现此错误:

For some reason though, when I add the second argument to the button function, it stops working. If I use the exact same code, it works fine, but when I add a second argument I get this error:

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

出什么问题了?

推荐答案

问题是 command 属性需要对函数的引用.当您执行 command = self.button(...)时,您将立即调用该函数,然后将函数的结果用作 command 属性的值.

The problem is that the command attribute expects a reference to a function. When you do command=self.button(...), you are immediately calling the function and then using the result of the function as the value for the command attribute.

如果要传递参数,则需要使用 lambda functools.partial .这个问题在这个网站上已经被问过很多次了.参见,例如,使用带有"command"参数的参数来调用函数.和"bind" python Tkinter:将参数传递给函数

If you want to pass arguments, you need to use lambda or functools.partial. This question has been asked many times on this site. See, for example, Calling functions with arguments on "command" and "bind" and python Tkinter: passing an argument to a function

这篇关于Tkinter中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆