1

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 :(

gunr2171
  • 16,104
  • 25
  • 61
  • 88
user2977984
  • 13
  • 1
  • 1
  • 4

1 Answers1

8

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

Peter Varo
  • 11,726
  • 7
  • 55
  • 77
  • A common mistake is to miss out the () at the end of tk.mainloop, which the latter will return a bound method. – Yaojin Mar 29 '20 at 03:25