Skip to content
Advertisement

How to make button using canvas in toplevel() Tkinter

I’m trying to make a button using canvas.create_window in toplevel() in Tkinter. Button is used to go back to main window. First “Start” button is displayed but second “Back” button is not. Code below.

from tkinter import *

win = Tk()

def play_button():
    win.withdraw()
    top = Toplevel()
    top.geometry("300x300")
    button_back = Button(top, text="Back", command=back_button)

    canvas_two = Canvas(top, width = 300, height = 300)    
    canvas_two.pack(fill="both", expand=True)         
    Button_reverse = canvas_two.create_window(0, 0, anchor="nw", window=button_back)
    top.resizable(False, False)

def back_button():
    win.deiconify()

win.geometry("300x300")

canvas = Canvas(win, width = 300, height = 300)
canvas.pack(fill="both", expand=True)      
button_play = Button(win, text="Play", command=play_button)
Play_button = canvas.create_window(0, 0, anchor="nw", window=button_play )

win.mainloop()

Advertisement

Answer

The problem is the ordering of creation of canvas_two and button_back. You need to create the Canvas first and then put the Button on top of it as shown below.

def play_button():
    win.withdraw()
    top = Toplevel()
    top.geometry("300x300")

    canvas_two = Canvas(top, width=300, height=300)
    canvas_two.pack(fill="both", expand=True)

    button_back = Button(top, text="Back", command=back_button)
    Button_reverse = canvas_two.create_window(0, 0, anchor="nw", window=button_back)
    top.resizable(False, False)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement