12

I am trying to learn Python and trying something GUI in Python and came across this Tkinter module. My code runs but the window does not appear when I run. My code is as follows:

from Tkinter import *
#to create a root window 
root = Tk()

The program runs, gives no errors but the window does not show up.

2
  • Yeah it is workinng now thanks... But where shall I put my buttons and all after root.mainloop()? Commented Oct 25, 2012 at 1:20
  • 1
    @JoelCornett, you saved my day after 9 years :-D Commented Sep 30, 2021 at 11:20

3 Answers 3

20

Add this to your code root.mainloop(), Here's a tutorial.

In response to your comment

#Also note that `from <module> import *` is generally frowned upon
#since it can lead to namespace collisions. It's much better to only
#explicitly import the things you need.
from Tkinter import Tk, Label
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

5

As other answers have pointed out, you need to call mainloop on the root object.

I recommend an OO-style of programming, and I also recommend not doing a global import (ie: not 'from Tkinter import *').

Here's a template I usually start out with:

import Tkinter as tk

class ExampleView(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        l = tk.Label(self, text="your widgets go here...", anchor="c")
        l.pack(side="top", fill="both", expand=True)

if __name__=='__main__':
    root = tk.Tk()
    view = ExampleView(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()

This makes it easy to keep your main logic at the start of the file, and keep the creation of the root and the calling of mainloop together, which I think makes the code a little bit easier to understand. It also makes reusing this code a little easier (ie: you could create a larger program where this is one of several windows that can be created)

Comments

2

Add root.mainloop() at the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.