Is the objects of tkinter.Tk independent of each other?

时间:2018-02-03 10:47:35

标签: python user-interface tkinter listbox tcl

I write a python script (named script2.py) which includes tkinter. To be convenient, I write a function at the bottom. It looks like:

import tkinter
import pygubu

class GuiApp2:
    def __init__(self,master):
        self.builder=pygubu.Builder()
        self.builder.add_from_file('test.ui')

        self.builder.get_object('Frame_main',master)
        self.list_box_a=self.builder.get_object('Listbox_a')

        self.lba_value_set=tkinter.StringVar()
        self.list_box_a['listvariable']=self.lba_value_set

    def set_value_set(self,the_value_set):
        self.lba_value_set.set(the_value_set)


def run(the_value_set):
    master=tkinter.Tk()
    app=GuiApp1(master)
    app.set_value_set(the_value_set)
    master.mainloop()

def main():
    run(['1','2','3'])

if __name__ == '__main__':
    main()

And then I write another script (named script1.py) which calls the function at the bottom of the script above. It is:

import tkinter
import pygubu

import script2

class GuiApp1:
    def __init__(self,master):
        self.builder=pygubu.Builder()
        self.builder.add_from_file('mainapp.ui')

        self.builder.get_object('Frame_main',master)
        self.button_show=self.builder.get_object('Button_show')

        self.button_show['command']=self.command_for_button_show

    def command_for_button_show(self):
        script2.run(['1','2','3'])


def main():
    master=tkinter.Tk()
    app=GuiApp1(master)
    master.mainloop()


if __name__ == '__main__':
    main()

When I run script2.py, everything is fine. But when I run script1.py which imports script2.py the Listbox in script2.py is empty.

Of course, these two scripts are not the files I use in my project. The files I really use is too long and difficult to read.

In order to find out the problem, I inserted several print functions in my script to show the values of the variable in my scripts. Finally, every print result is fine except the Listbox.

Thus I simplified the real scripts to these scripts which are easy to read.

I guess maybe the master(tkinter.Tk()) in script1.py affect the master in script2.py. Because the logic of GUI Management in tkinter is different from it in dotNet.

Is there anyone who's met a similar problem or have some idea about that?

1 个答案:

答案 0 :(得分:3)

是的,他们是独立的。每次创建Tk的实例时,都会创建嵌入式Tcl解释器的新实例。因此,一个小部件对另一个小部件一无所知。

编写良好的tkinter程序永远不应创建Tk的多个实例。如果您需要其他窗口,则应创建Toplevel的实例。您也应该只调用mainloop()一次。