Reputation: 53
I am trying to create a basic Tkinter window.
According to on-line tutorials, to create a window one must use the following:
import Tkinter
window=Tkinter.Tk()
window.mainloop()
But when I try the same code python directly displays the window in window=Tkinter.Tk()
and window.mainloop()
has no effect.
Can anyone explain why ?
EDIT: The code works perfectly when I put it in a file and run it. It just doesn't work from interactive prompt.
Upvotes: 2
Views: 2445
Reputation: 94881
The call to mainloop
is there so that you can interact with the Window once it's created. If you had a Python script that only did this:
import Tkinter
window = Tkinter.Tk()
The script would exit immediately after window
was created, so you'd be luckily to even see it get drawn before it disappeared as the script exited. (That is if window
was even drawn at all; in my tests on both Linux and Windows, window
was never drawn unless mainloop
was called; even if I put a call to time.sleep
after the Tkinter.Tk()
call, window
would only be drawn without a mainloop
call in the interactive prompt).
The mainloop()
also (and most importantly) allows Tkinter
to listen for events to occur on the Tk
object, such as pressing buttons, radios, etc. that might be embedded in it, and dispatch those events to methods you have bound to the event being triggered. Without that functionality you'd just have a window that you can look at and not much else.
Upvotes: 1