user2977984
user2977984

Reputation: 13

Python Tkinter not working in a .py file

My problem is that my python code is not working when I run it as a .py file. Here is the code:

import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()

There is more code to it than that, but that is the relevant stuff. It works fine when I use the python shell or type it directly into the python console, but when I run it as a .py file, it seems to skip this code and go on to the rest, without displaying a canvas. I am using windows, but I am not sure what version of python I'm using.

I was also using from * import tkinter before, with relevant changes to the code and i changed it to try and help fix it. It didn't work :(

Upvotes: 1

Views: 14385

Answers (1)

Peter Varo
Peter Varo

Reputation: 12190

You are missing the eventloop at the end:

import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()

# Enter into eventloop <- this will keep
# running your application, until you exit
tk.mainloop()

Only a personal recommendation: don't use tk as a variable name, use app or root or even win/window

Upvotes: 8

Related Questions