简体   繁体   English

Python Tkinter将self作为按钮命令参数传递

[英]Python Tkinter passing self as button command parameter

I have a noob question: 我有一个菜鸟问题:

I am trying to make a class "Field" that inherits everything from Tkinter's Button class but also contains the additional attribute "location" and a method to get that attribute. 我正在尝试创建一个“字段”类,该类继承Tkinter的Button类的所有内容,但还包含其他属性“位置”和获取该属性的方法。 Having implemented that, I make in instance of the new "Field" class and try to have the Field's command call its function to get its location attribute: 实现了这一点之后,我以新的“ Field”类为例,尝试让Field的命令调用其函数以获取其location属性:

from Tkinter import *

class Field(Button):
    def __init__(self, location, **k):
        Button.__init__(self, **k)
        self.location = location

    def getLoc(self):
        return self.location

root=Tk()
c = Field(2, text="Text", command = lambda: self.getLoc)
c.pack()
root.mainloop()

The root window with the button appears but upon pressing it, the following error occurs: 出现带有按钮的根窗口,但按下该按钮会发生以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\PC\Desktop\test2.py", line 12, in <lambda>
    c = Field(2, text="Text", command = lambda: self.getLoc)
NameError: global name 'self' is not defined

What should I do to make it see the fact that I want the recently instantiated "Field" to be the "self" whose location it should return? 我应该怎么做才能使我希望最近实例化的“字段”成为应返回其位置的“自身”这一事实?

Thank you in advance 先感谢您

Edit: sorry I was completely off about the original response about doing lambda self: self.getLoc , corrected answer (and checked by running the code this time!) 编辑:对不起,我完全lambda self: self.getLoclambda self: self.getLoc的原始响应lambda self: self.getLoc ,更正了答案(并且这次通过运行代码进行检查!)

You should probably configure the command after you create the button, that way you can explicitly refer to the button. 创建按钮后,您可能应该配置命令,这样就可以显式引用该按钮。

root=Tk()
c = Field(2, text="Text")
c.config(command=c.getLoc)
c.pack()
root.mainloop()    

You can read more about the config method of Tkinter objects (and much more) on effbot.org . 您可以在effbot.org上了解有关Tkinter对象的config方法的更多信息(以及更多信息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM