Reputation: 8759
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()
Upvotes: 1
Views: 3268
Reputation: 386240
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.
Upvotes: 2