【发布时间】:2015-08-21 19:27:49
【问题描述】:
我正在创建一个 Python (3.4.3) - tkinter 程序,我想知道是否可以从另一个 class 内部引用 def (self.get_details) 来获取按钮的命令。我无法在任何地方找到这个问题的答案,所以我想我只是问问。
例子:
import tkinter as tk
...
class Widgets(tk.Frame):
def __init__(self, parent):
tk.Frame.__init___(self, parent)
self.parent = parent
self.initUI()
def initUI():
# Lots of other different tkinter widgets go here
self.button = tk.Button(command=App(get_details))
self.button.pack()
class PopUp(tk.TopLevel): ....
class App(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def get_details(self):
# Complete a function
def initUI(self):
self.parent.title("My Application")
self.style = Style()
self.style.theme_use("default")
self.pack()
self.widgets = Widgets(self)
self.widgets.pack(side="top", anchor="center", fill="both", expand=True)
if __name__ == "__main__":
root = tk.Tk()
App(root).pack(side="top", fill="both", expand=True)
root.resizable(0,0)
root.mainloop()
所以我想要一个属于Widgets() 类的按钮来调用属于App() 类的def get_details(self) 命令,其中包含Widgets() 类。
我希望我的描述性足够,这个问题很难用词来形容。总的来说,我对 Python 还是有点陌生。谢谢!
编辑:
按照建议,我将其更改为self.parent.get_details(),这很有效!但是,当我从 def get_details() 中的 Widgets() 类引用 tkinter 小部件时,例如:self.button,我得到:
AttributeError: 'App' object has no attribute 'button'
所以我尝试将按钮引用为:self.parent.button,我收到了:
AttributeError: 'tkapp' object has no attribute 'button'
我应该如何调用/引用按钮?谢谢!
【问题讨论】:
-
self.parent.get_details()应该可以工作。你试过吗? -
主要工作,见编辑。
-
要在
get_details中引用Widgets对象中的某些内容,请使用self.widgets.button。无论您在哪个对象中,self指的是该对象的一个实例。
标签: python class button tkinter function