Python Tkinter实例没有'tk'属性。

3

属性错误:MyGUI实例没有“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()

有什么问题吗? 谢谢

2个回答

4

您应该调用Frame的超级构造函数。我不确定,但我猜这将设置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,但我认为上述方法更适合创建框架,例如请参见这里。)


1
这个错误通常意味着你正在调用SomeTKSuperClass.__init__,并忘记了第一个参数,它必须是self。请记住,在这种情况下,__init__是一个类方法(静态函数),而不是实例方法,这意味着你必须明确地传递self

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接