1

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()
  • Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – jasonharper Feb 06 '21 at 19:08
  • 1
    Please fix the indentation of your code. – Bryan Oakley Feb 06 '21 at 19:14
  • The code in your question **will** produce errors. Please edit your question again and provide a [mre]. – martineau Feb 06 '21 at 19:41
  • @jasonharper: I don't think that question is a dup (yet). The `background_two` in the OP's code isn't being used. – martineau Feb 06 '21 at 19:47

1 Answers1

0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301