如何在Tk()在其他类中定义的类中创建StringVar?

时间:2015-11-26 10:13:18

标签: python tkinter

在这里,我需要创建一个DropDown类&稍后将其添加到rootmain GUI。但是Tkinter.StringVar()正在抛出错误

`Traceback (most recent call last):
  File "D:/Testing/Tiks/main2.py", line 64, in <module>
    d = Droppy(application)
  File "D:/Testing/Tiks/main2.py", line 45, in __init__
    self.control_variable = Tkinter.StringVar()
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 251, in __init__
    Variable.__init__(self, master, value, name)
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 182, in __init__
    self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
Exception AttributeError: "StringVar instance has no attribute '_tk'" in <bound method StringVar.__del__ of <Tkinter.StringVar instance at 0x0236F7B0>> ignored`

我的代码就是这个

import Tkinter


class App(object):

    def __init__(self):
        self.root = Tkinter.Tk()
        ############################
        ############################
        self.root.mainloop()


class Droppy(object):

    def __init__(self, frame=None):
        # if frame is None:
        #     raise Exception
        self.frame = frame
        self.control_variable = Tkinter.StringVar()
        self.control_variable.set("Choose Options")
        self.dropDown = None

    def dropIt(self):
        self.dropDown = Tkinter.OptionMenu(self.frame.root, self.control_variable, "Rules", "Processing", "Output",
                                           "Actions")
        self.dropDown.pack()

if __name__ == '__main__':
    application = App()
    # application = Droppy()
    # application.dropIt()
    d = Droppy(application)
    d.dropIt()

现在我知道Tkinter.Tk()之前的Tkinter.StringVar()可以解决这个问题,但是我不能把Tkinter.Tk()和Tkinter.StringVar()`放在同一个类中。我怎样才能避免这个问题?任何人都可以帮忙吗

2 个答案:

答案 0 :(得分:2)

mainloop是无限循环,它一直运行直到你关闭Tk窗口 当Droppy已经关闭时,您可以创建App

您必须在mainloop之前创建对象 - 例如在App.__init__内。

import Tkinter


class App(object):

    def __init__(self):
        self.root = Tkinter.Tk()
        ############################
        d = Droppy(self)
        d.dropIt()
        ############################
        self.root.mainloop()


class Droppy(object):

    def __init__(self, frame=None):
        # if frame is None:
        #     raise Exception
        self.frame = frame
        self.control_variable = Tkinter.StringVar()
        self.control_variable.set("Choose Options")
        self.dropDown = None

    def dropIt(self):
        self.dropDown = Tkinter.OptionMenu(self.frame.root, self.control_variable, 
                                           "Rules", "Processing", "Output",
                                           "Actions")
        self.dropDown.pack()

if __name__ == '__main__':
    application = App()

答案 1 :(得分:0)

作为替代方案,您可以在main中调用mainloop():

if __name__ == '__main__':
    application = App()
    d = Droppy(application)
    d.dropIt()
    application.root.mainloop()