Question

I'm just beginning to learn tkinter and I'm missing something fundamental here. When I try to do nothing but create a blank window, I get mixed results. Here's the code:

from tkinter import *
from tkinter import ttk

root = Tk()

And what happens is that if I run it in the python shell it works perfectly (like by simply hitting F5 in the IDLE editor) and a little blank window pops up and stays open til I close it.

But if I simply double click the .pyw file, nothing happens at all. Same if I save it as a .py.

If I save it as .py and add input() to the end, THEN the little blank window pops up and stays open. Adding that to the .pyw has no effect; still nothing happens. Which makes partial sense since .pyw hides the console.

But what am I doing wrong here? What do I have to do to make a .pyw which simply shows a blank window and does not show the console?

Was it helpful?

Solution

The problem is not the file type, as you will be pleased to know. Saving as a .pyw just means that the console will not show up when the file is run (no strings attached, the code runs exactly the same)- and there are no exceptions whatever the code may be.

What you need to do is add this to the end of your code (this is necessary for all tkinter programs):

root.mainloop()  # this will launch the window

The window won’t appear until we’ve entered the tkinter event loop and the program will stay in the event loop until we close the window.

The event loop doesn’t only handle events from the user (such as mouse clicks and key presses) or the windowing system (such as redraw events and window configuration messages), it also handle operations queued by tkinter itself. Among these operations are geometry management (queued by the .pack() method) and display updates. This also means that the application window will not appear before you enter the mainloop().

I think the reason why you do not need to call mainloop() in IDLE is because IDLE itself is a tkinter program, and it already has an event loop going. So possibly the tkinter code you are typing into the shell is getting bound to IDLE's event loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top