【发布时间】:2020-03-07 09:21:11
【问题描述】:
我想要完成的是一种在另一个类实例中更改变量的方法。我一直在摸索,试图了解这是如何(或是否)可能的。
如何更新类中
self.lblvar的值MainWindow来自班级SecondWindow?
这是我用来检验我的理论的东西:
from tkinter import *
class MainWindow:
def __init__(self, rootWin):
self.rootWin = rootWin
self.rootWin.geometry('400x200')
self.mainMenu = Menu(self.rootWin)
self.mainMenu.add_command(label = 'Open Second Window', command = self.openSecondWindow)
self.lblvar = StringVar()
self.lblvar.set('Change Me!')
self.lbl = Label(rootWin, textvariable = self.lblvar)
self.lbl.pack()
self.rootWin.config(menu = self.mainMenu)
def openSecondWindow(self):
self.secondWin = Tk()
self.secWin = SecondWindow(self)
self.secondWin.mainloop()
class SecondWindow:
def __init__(self, parent):
self.parent = parent
self.btn = Button(self, label = 'Change Label?', command = self.changeOther)
self.btn.pack()
def changeOther(self):
self.parent.lblvar.set('Changed it!')
def main():
root = Tk()
mainWin = MainWindow(root)
root.mainloop()
if __name__ == "__main__":
main()
在 Python 类方面我是个新手,所以任何有关这方面的指导和/或解释都将不胜感激!
编辑:将原始问题更改为更清晰的问题,以帮助对该主题进行进一步搜索
【问题讨论】:
-
抱歉,没有更多关于您要完成的工作的解释,您的问题不清楚。
-
嘿@ThierryLathuille!我想要完成的是创建一个辅助“选项”窗口来调整主窗口。在这种情况下,第二个窗口仅对主窗口的标签对象进行更改。
-
您是在寻找 Tkinter 特定的答案(即我可以更改其他窗口中的属性吗?),或者天气这个概念在 python 中是否可行?
-
@Aleon 是正确的。我正在尝试在另一个 Tkinter 窗口中修改标签和其他对象
-
@Aleon 如果他们修复了
openSecondWindow,OP 应该可以正常工作。这种方法并没有像他们认为的那样做。虽然我会重写它以继承Tk和Toplevel以解决其他一些问题。
标签: python class tkinter class-attributes