Search code examples
pythontkintercustomtkinter

How do I fix a weird rectangle appearing after I remove an entry widget in my Tkinter program?


I´m creating an interactive board programm and I run into a problem.

After I´m destroying entry I have a weird rectangle in the place of previous entry. Do I only have this problem? I'm using windows.

Here's my code:

from customtkinter import *

set_appearance_mode('System')
set_default_color_theme('dark-blue')

window = CTk()  # Window
window.geometry("800x520")

def destroy(event):
    event.widget.destroy()

def text(event):
    entry = CTkEntry(window, width=100, font=('Arial', 24), text_color='black')
    entry.bind("<Button-3>", destroy)
    canvas.create_window(event.x, event.y, window=entry)

canvas = CTkCanvas(window, bg='white', bd=2, relief=SUNKEN, height=430, width=700)
canvas.place(x=60, y=50)
canvas.bind("<Button-1>", text)

window.mainloop()  # Loop

I think I have problems because of line canvas.create_window(event.x, event.y, window=entry), but in my programm I cannot delete this line of code.


Solution

  • A CTkEntry widget is more than a single widget, it's a frame with a CTkCanvas and an Entry widget. Your binding only destroys the inner Entry widget.

    A simple solution is to add a binding that destroys the frame when the entry widget is destroyed, with something like entry.bind("<Destroy>", lambda event: entry.destroy()):

    def text(event):
        entry = CTkEntry(window, width=100, font=('Arial', 24), text_color='black')
        entry.bind("<Button-3>", destroy)
        entry.bind("<Destroy>", lambda event: entry.destroy())
        canvas.create_window(event.x, event.y, window=entry)