How does creating two instances of Tk work with one mainloop?

守給你的承諾、 提交于 2019-12-24 14:51:05

问题


How does adding master = Tk() into the __init__ of a subclass of tkinter.Frame
produce two windows (app and app2) when only app.mainloop() is called?

from tkinter import Frame,Button,Tk

class Application(Frame):

    def say_hi(self):
        print('Hello world?!')

    def close(self):
        self.master.destroy()

    def createWidgets(self):
        self.quit_b = Button(self, width=12, text='Quit', bg='tan',
                    command=self.close)
        self.quit_b.grid(row=0, column=0, padx=8, pady=8)

        self.hello_b = Button(self, width=12, text='Hello',
                    command=self.say_hi)
        self.hello_b.grid(row=0, column=1, padx=8, pady=8)

    def __init__(self):
        master = Tk() # <------------------------ ! see here !
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()


app = Application()
app.master.title('Hello world!')

app2 = Application()
app2.master.title('Hello world! 2')

app.mainloop()

回答1:


You cannot create two instances of the class Tk, and it's somewhat unusual to instantiate it within the __init__ of another class. Your code should work, but I've never seen it done that way.

You need to create an instance of Tk before creating any other widgets. Since your main app is a subclass of Frame, you're partially creating the instance of a Frame before initializing Tkinter which is simply not the way it should be done. It might work, but the behavior is undefined.

Instead, it's generally better to create your application as a subclass of Tk:

from Tkinter import tk
class Application(tk.Tk):
    ...

app = Application(...)
app.mainloop()

OR, create an instance of Tk at the global scope, and pass it as an argument to your other widgets:

from Tkinter import tk
class Application(tkFrame):
    ...
root = tk.Tk()
myframe = Application(root)
root.mainloop()

If you need more than one window, create additional windows with the Toplevel class.



来源:https://stackoverflow.com/questions/9640013/how-does-creating-two-instances-of-tk-work-with-one-mainloop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!