【问题标题】:Can you make a button create itself?你能让一个按钮自己创建吗?
【发布时间】:2023-03-08 23:15:01
【问题描述】:

所以我想做一个按钮,当我点击它时,它会被删除并出现另一个,并且可以无限次这样做

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 进行了裁判。但是当我按下新按钮时没有任何反应。谁能帮帮我?

【问题讨论】:

  • 如果您想保留参考,请分配一个真实姓名和append()它到列表中。
  • 为什么要删除并重新创建一个按钮而不是重复使用它?您可以更改按钮的所有属性。销毁一个按钮并重新创建一个按钮而不是重用它似乎没有多大意义。
  • 你知道你做了a+a+1。我想你想要a = a+1。如果是这样的话a += 1 更好

标签: python tkinter button tkinter-canvas


【解决方案1】:

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

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 画布中移动窗口而不是删除并重新创建它会更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    相关资源
    最近更新 更多