gpt4 book ai didi

python-2.7 - Python Tkinter 实例没有属性 'tk'

转载 作者:行者123 更新时间:2023-12-03 13:20:47 25 4
gpt4 key购买 nike

AttributeError: MyGUI instance has no attribute 'tk'

另外,如何使创建的窗口具有固定大小并且不能用鼠标调整大小?或者在通过单击按钮更改标签值之后。

我的代码:

from Tkinter import*

class MyGUI(Frame):

def __init__(self):
self.__mainWindow = Tk()

#lbl
self.labelText = 'label message'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)

#buttons
self.hi_there = Button(self.__mainWindow)
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.testeo

self.QUIT = Button(self.__mainWindow)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit

#place on view
self.depositLabel.pack()
self.hi_there.pack() #placed in order!
self.QUIT.pack()

#What does it do?
mainloop()

def testeo(self):

self.depositLabel['text'] = 'c2value'

print "testeo"

def depositCallBack(self,event):
self.labelText = 'change the value'
print(self.labelText)
self.depositLabel['text'] = 'change the value'

myGUI = MyGUI()

怎么了?谢谢

最佳答案

您应该调用Frame 的 super 构造函数。不确定,但我猜这将设置 quit 命令所依赖的 tk 属性。之后,无需创建您自己的 Tk() 实例。

def __init__(self):
Frame.__init__(self)
# self.__mainWindow = Tk()

当然,您还必须相应地更改小部件的构造函数调用,例如,

self.hi_there = Button(self)  # self, not self.__mainWindow

或更好(或至少更短):直接在构造函数中设置所有属性:

self.hi_there = Button(self, text="Hello", command=self.testeo)

同时将 self.pack() 添加到您的构造函数中。

(或者,您可以将退出命令更改为 self.__mainWindow.quit,但我认为以上是创建框架的更好样式,请参见例如 here。)

关于python-2.7 - Python Tkinter 实例没有属性 'tk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19533189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com