我正在创建一个Python(3.4.3) - tkinter程序,我想知道是否可以从另一个def
内部引用class
(self.get_details)来获取按钮& #39; s命令。我无法在任何地方找到这个问题的答案,所以我想我只是问。
示例:
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()
的按钮来调用属于类def get_details(self)
的{{1}}命令,该类具有App()
类装在里面。
我希望我的描述性足够,很难说出这个问题。我总是对Python有点新意。谢谢!
编辑:
根据建议我将其更改为Widgets()
,这有效!但是,当我从self.parent.get_details()
Widgets()
中的def get_details()
类引用tkinter小部件时,例如:self.button
,我得到:
AttributeError: 'App' object has no attribute 'button'
所以我尝试将按钮引用为:self.parent.button
,我收到了:
AttributeError: 'tkapp' object has no attribute 'button'
我应该如何调用/引用按钮?谢谢!
答案 0 :(得分:2)
在App
中,您创建一个Widgets
对象并保存对其名为self.widgets
的引用。执行此操作时,将对App
对象的引用传递给Widgets
对象。 App
实例引用在Widgets
对象中保存为self.parent
。请注意,self
的这两种用法指的是不同的对象:在App
中,self
指的是该App
对象的当前实例。在Widgets
中,self
引用该Widgets
对象的当前实例。要引用其他类中的内容,您必须使用正确的引用并遵循路径。
在App
个实例中:
self this App instance
.widgets the Widgets instance it contains
.button the button in that Widget instance
在Widgets
个实例中:
self this Widgets instance
.parent the App object that created this Widgets object
.get_details the get_details function in the parent App object
在下文中,我修复了代码的剩余位(...
导致语法错误,Style
未定义等)并提供了一个小例子,如何从另一个引用每个对象。按钮最初表示"你好",你可以改为"再见"点击它。
import tkinter as tk
class Widgets(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
# Lots of other different tkinter widgets go here
self.button = tk.Button(text='hello', command=self.parent.get_details)
self.button.pack()
class App(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def get_details(self):
self.widgets.button.config(text='goodbye')
def initUI(self):
self.parent.title("My Application")
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()