0

I cant create any shape with tkinter. Problem is only in this code, any other works fine.

import tkinter

okno = tkinter.Tk()
okno.geometry("1280x720")

platno = tkinter.Canvas(width = 1280, height = 720)
platno.pack()

okno.resizable(False, False)
okno.mainloop()

platno.create_rectangle(50,50,100,100)

I was trying to make a little game for fun. Ive started with window i made it i cant resize it. Then tried to create a rectangle at the canvas. But it doesnt work. This is the error:

Traceback (most recent call last):
  File "C:\Users\Motix\Desktop\LOLKO.py", line 12, in <module>
    platno.create_rectangle(50,50,100,100)
  File "C:\Users\Motix\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 2835, in create_rectangle
    return self._create('rectangle', args, kw)
  File "C:\Users\Motix\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 2805, in _create
    return self.tk.getint(self.tk.call(
_tkinter.TclError: invalid command name ".!canvas"
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Moti
  • 1

2 Answers2

0

Edit:

On Raspberry Pi running Linus Python 3.9.x. I don't see no error. But got a blank window with no GUI.

If I move okno.mainloop() to the end of the bottom, it would work.

On pc, running on Windows 10, Python 3.12.0b2. I ran your code and got error message saying that _tkinter.TclError: invalid command name ".!canvas".

If I move okno.mainloop() to the end of the bottom, it would work.

Good NEWS. Today, I updating Python 3.12.0rc1.

If I move okno.mainloop() to the end of the bottom, it would work.

_tkinter.TclError: invalid command name ".!canvas"

Your problem is causing that you are running older version. You should be updating Python version.

The okno.mainloop() should not put anywhere before widget.

Always call okno.mainloop() as the last logical line of code in your program. That's how Tkinter was designed to be used. So that we can see the still screen.

Move the mainloop() to the bottom.

platno.create_rectangle(50,50,100,100)
okno.mainloop()

Screenshot:

enter image description here

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
0

The root of the problem is that you're trying to call a method on the canvas object, but the canvas object has been destroyed by the time you try to create the rectangle. The message invalid command name ".!canvas" means that the canvas no longer exists.

Note: .!canvas is the internal name of the canvas object stored in the variable canvas. It is automatically computed by tkinter unless you explicitly give it a name.

The reason this is happening is that your call to mainloop() won't return until after the root window has been destroyed. When it is destroyed, all of its children will be destroyed.

The simple solution in this case is to move the call to create_rectangle before the call to mainloop so that it can work while the window still exists.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685