如何在 toplevel() Tkinter 中使用 canvas 制作按钮

How to make button using canvas in toplevel() Tkinter

我正在尝试使用 Tkinter 中的 toplevel() 中的 canvas.create_window 创建一个按钮。按钮用于返回主window。显示第一个“开始”按钮,但不显示第二个“后退”按钮。下面的代码。

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()

问题是 canvas_twobutton_back 的创建顺序。您需要先创建 Canvas,然后将 Button 放在上面,如下所示。

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)