你能让一个按钮自己创建吗?

时间:2021-03-02 20:19:58

标签: python tkinter button tkinter-canvas

所以我想制作一个按钮,当我点击它时,它会被删除并出现另一个,并且可以无限次地完成

a=0
button1 = [1,2,3,4,5,6]

def ButtonClick():

     global a
     #Destroys the first button
     button1[a].destroy()

     a+a+1

     #Making new button, that should do the same as the old button
     button1[a] = tk.Button(text='hello',command=ButtonClick)
     canvas1.create_window(250+a*50, 140, window=button1[a])


  

button1[a] = tk.Button(text='hello',command=ButtonClick)
canvas1.create_window(100, 140, window=button1[a])

正如你所看到的,新按钮也使用了 command=ButtonClick,所以当我按下创建的按钮时,它应该和旧按钮一样,但它没有,我不是确定为什么,因为当我更改新按钮上的命令时,它会显示错误,因此它以某种方式裁判 def ButtonClick。但是当我按下新按钮时没有任何反应。谁能帮帮我?

1 个答案:

答案 0 :(得分:0)

为了销毁和重建按钮,您必须将其设为全局。这是一个可以被自己的函数销毁的按钮的工作示例,只能再次创建:

def ButtonClick():
    global root
    root.b.destroy()
    root.b = Button(root,text="Hello",command=ButtonClick)
    root.c.create_window(250+root.button1[root.bnumber]*50,140,window=root.b)
    if root.bnumber<len(root.button1)-1:root.bnumber+=1
    
global root
root = Tk()
root.geometry('800x600')
root.resizable(0, 0)
root.c = Canvas(root,bg="#ffffff",width=800,height=600)
root.c.grid(row=0,column=0,sticky=W+S+E+N)

root.b = Button(root,text="Hello",command=ButtonClick)
root.c.create_window(100,140,window=root.b)
root.button1 = [1,2,3,4,5]
root.bnumber = 0

我制作了您的 button1 列表和 tkinter 小部件的当前索引 (a) 属性,因此只要函数可以访问小部件,就可以访问它。

然而,对于这个例子,在 tkinter 画布内移动窗口会更容易,而不是删除并重新创建它。

相关问题