Skip to content Skip to sidebar Skip to footer

Hiding/displaying A Canvas

How do you hide a canvas so it only shows when you want it displayed? self.canvas.config(state='hidden') just gives the error saying you can only use 'disabled' or 'normal'

Solution 1:

In the comments you say you are using pack. In that case, you can make it hidden by using pack_forget.

import tkinter as tk

def show():
    canvas.pack()

def hide():
    canvas.pack_forget()

root = tk.Tk()
root.geometry("400x400")

show_button = tk.Button(root, text="show", command=show)
hide_button = tk.Button(root, text="hide", command=hide)

canvas = tk.Canvas(root, background="pink")
show_button.pack(side="top")
hide_button.pack(side="top")
canvas.pack(side="top")

root.mainloop()

However, it's usually better to use grid in such a case. pack_forget() doesn't remember where the widget was, so the next time you call pack the widget may end up in a different place. To see an example, move canvas.pack(side="top") up two lines, before show_button.pack(side="top")

grid, on the other hand, has a grid_remove method which will remember all of the settings, so that a subsequent call to grid() with no options will put the widget back in the exact same spot.

Post a Comment for "Hiding/displaying A Canvas"