Python Forum
tkinter.TclError: can't invoke "canvas" command
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
tkinter.TclError: can't invoke "canvas" command
#1
I am getting this tcl error and unable to solve it. Here is the full exception. This happens when I exit the program
Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\INDIAN\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "C:\Users\INDIAN\Desktop\python exercises\pygametooth\untiltledtry 15-2-23.py", line 65, in select_folder canvas.delete("all") File "C:\Users\INDIAN\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2818, in delete self.tk.call((self._w, 'delete') + args) _tkinter.TclError: invalid command name ".!canvas" Traceback (most recent call last): File "C:\Users\INDIAN\Desktop\python exercises\pygametooth\untiltledtry 15-2-23.py", line 135, in <module> canvas = Canvas(root, width=800, height=500, bg="white") File "C:\Users\INDIAN\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2683, in __init__ Widget.__init__(self, master, 'canvas', cnf, kw) File "C:\Users\INDIAN\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2567, in __init__ self.tk.call( _tkinter.TclError: can't invoke "canvas" command: application has been destroyed >>>
import tkinter as tk
from tkinter import Canvas, NW
from tkinter import filedialog
import os
import pygame
import cv2
import numpy as np
from PIL import Image, ImageTk


image_tk = None # Placeholder variable for PhotoImage

# Initialize Pygame
pygame.init()





def select_folder():
    # Open a file dialog to select the folder
    root.filename = filedialog.askdirectory()

    # Load the images from the selected folder
    images = []
    for f in os.listdir(root.filename):
        if f.endswith((".png", ".jpg", ".bmp", ".dcm")):
            image = cv2.imread(os.path.join(root.filename, f))
            if image is not None:
                images.append(image)

    # Set the initial image
    current_image = 0

    # Main loop
    running = True
    while running:
        # Handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    current_image = (current_image - 1 + len(images)) % len(images)
                elif event.key == pygame.K_RIGHT:
                    current_image = (current_image + 1) % len(images)

        
        
        # Clear the canvas
        canvas.delete("all")

        # Get the dimensions of the current image
        height, width = images[current_image].shape[:2]
        # Set the rotation angle
        angle = 90

        # Calculate the center of the image
        center = (width // 2, height // 2)

        # Create the rotation matrix
        rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
        # Calculate the new dimensions of the rotated image
        new_width, new_height = height, width

        # Rotate the image
        rotated = cv2.warpAffine(images[current_image], rotation_matrix, (new_width, new_height))

        # Convert the BGR image to RGB
        rgb_image = cv2.cvtColor(rotated, cv2.COLOR_BGR2RGB)

         

        # Convert the OpenCV image to a PIL ImageTk
        pil_image = Image.fromarray(np.rot90(rgb_image, 3))
##        pil_image = Image.fromarray(rgb_image)
        image_tk = ImageTk.PhotoImage(image=pil_image)

        # Display the image in the tkinter window
        canvas.create_image(0, 0, image=image_tk, anchor=NW)
        canvas.image = image_tk

        # Update the screen
        root.update()

def exit_program():
    root.destroy()

def on_key_press(event):
    if event.keysym == "Left":
        pygame.event.post(pygame.event.Event(pygame.KEYDOWN, {"key": pygame.K_LEFT}))
    elif event.keysym == "Right":
        pygame.event.post(pygame.event.Event(pygame.KEYDOWN, {"key": pygame.K_RIGHT}))

# Create the GUI
##root = tk.Tk()
root.title("Multi-angle Image Viewer")
root.geometry("800x600")

# Add a button to select the folder
button = tk.Button(root, text="Select Folder", command=select_folder)
button1 = tk.Button(root, text="Exit", command=exit_program)
button.pack()
button1.pack()

# Create the canvas to display the images
canvas = Canvas(root, width=800, height=500, bg="white")
canvas.pack()

# Bind the arrow keys to the canvas
canvas.bind("<Key>", on_key_press)
canvas.focus_set()

# Run the GUI


# Run the GUI
root.mainloop()

### Create the canvas to display the images
canvas = Canvas(root, width=800, height=500, bg="white")
canvas.pack()

# Run the GUI
root.mainloop()
Reply


Messages In This Thread
tkinter.TclError: can't invoke "canvas" command - by cybertooth - Feb-15-2023, 10:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] tkinter.TclError: expected integer but got " " TWB 2 3,977 Feb-19-2023, 05:11 PM
Last Post: TWB
  [Tkinter] Clickable Rectangles Tkinter Canvas MrTim 4 9,206 May-11-2021, 10:01 PM
Last Post: MrTim
  [Tkinter] Draw a grid of Tkinter Canvas Rectangles MrTim 5 8,253 May-09-2021, 01:48 PM
Last Post: joe_momma
  [Tkinter] _tkinter.TclError: can't invoke "destroy" command: application has been destroyed knoxvilles_joker 6 16,118 Apr-25-2021, 08:41 PM
Last Post: knoxvilles_joker
  .get() invoke after a button nested press iddon5 5 3,423 Mar-29-2021, 03:55 AM
Last Post: deanhystad
Thumbs Up tkinter canvas; different page sizes on different platforms? philipbergwerf 4 4,311 Mar-27-2021, 05:04 AM
Last Post: deanhystad
  Continue command in python tkinter? MLGpotato 7 8,795 Mar-27-2021, 04:59 AM
Last Post: deanhystad
  how to resize image in canvas tkinter samuelmv30 2 18,104 Feb-06-2021, 03:35 PM
Last Post: joe_momma
  "tkinter.TclError: NULL main window" Rama02 1 6,008 Feb-04-2021, 06:45 PM
Last Post: deanhystad
  how to rotate lines in tkinter canvas helpmewithpython 1 3,524 Oct-06-2020, 06:56 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020