2

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.

dano
  • 91,354
  • 19
  • 222
  • 219
  • Are you doing this via the interactive prompt? – dano Jun 30 '14 at 15:29
  • What do you mean by "directly" and "has no effect"? When I put your code in a file and do "python the_file.py", it works as expected. – Bryan Oakley Jun 30 '14 at 16:06
  • @dano yes, via the prompt. – Aaditya M Nair Jun 30 '14 at 16:08
  • possible duplicate of [What magic prevents Tkinter programs from blocking in interactive shell?](http://stackoverflow.com/questions/20891710/what-magic-prevents-tkinter-programs-from-blocking-in-interactive-shell) – dano Jun 30 '14 at 16:27

1 Answers1

1

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.

dano
  • 91,354
  • 19
  • 222
  • 219
  • But I actually have a window open at `window=Tkinter.Tk()` . I would have posted an image but I don't have enough reputation. – Aaditya M Nair Jun 30 '14 at 16:22
  • @AadityaMNair Yeah, it will show up in the interactive prompt for me, too. It won't show up if I put it in a Python script and run it, which is how you normally use GUI applications. – dano Jun 30 '14 at 16:25