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.
JavaScript
x
27
27
1
from tkinter import *
2
3
win = Tk()
4
5
def play_button():
6
win.withdraw()
7
top = Toplevel()
8
top.geometry("300x300")
9
button_back = Button(top, text="Back", command=back_button)
10
11
canvas_two = Canvas(top, width = 300, height = 300)
12
canvas_two.pack(fill="both", expand=True)
13
Button_reverse = canvas_two.create_window(0, 0, anchor="nw", window=button_back)
14
top.resizable(False, False)
15
16
def back_button():
17
win.deiconify()
18
19
win.geometry("300x300")
20
21
canvas = Canvas(win, width = 300, height = 300)
22
canvas.pack(fill="both", expand=True)
23
button_play = Button(win, text="Play", command=play_button)
24
Play_button = canvas.create_window(0, 0, anchor="nw", window=button_play )
25
26
win.mainloop()
27
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.
JavaScript
1
12
12
1
def play_button():
2
win.withdraw()
3
top = Toplevel()
4
top.geometry("300x300")
5
6
canvas_two = Canvas(top, width=300, height=300)
7
canvas_two.pack(fill="both", expand=True)
8
9
button_back = Button(top, text="Back", command=back_button)
10
Button_reverse = canvas_two.create_window(0, 0, anchor="nw", window=button_back)
11
top.resizable(False, False)
12