【问题标题】:Get the index of a button (while pressing) which is in an array获取数组中按钮的索引(按下时)
【发布时间】:2019-12-24 12:52:20
【问题描述】:

我在数组中保存了一些按钮:

buttons = []
labels.append(tk.Label(fr2, text="", pady=15))
labels.append(tk.Label(fr3, text="", pady=15))

稍后我访问数据库表并使用“for in”循环该表,以便从程序中的表中获取所有行。对于每一行,我都会激活一个带有网格的按钮。

i = 0
    if len(records) > 0:
        for row in records:
            print("current_date", ", target date")
            print(current_date, row[2])

            date = current_date - row[2]

            labels[i] = tk.Label(fr2, text=row[1], pady=15)
            labels[i].grid(row=i, column=0, sticky='we')
            labels[i+1] = tk.Label(fr3, text=date, pady=15)
            labels[i+1].grid(row=i, column=0, sticky='we')
            buttons[i] = tk.Button(fr4, text="Restart", command=restart, pady=13)
            buttons[i].grid(row=i, column=0, sticky='we')
            buttons[i+1] = tk.Button(fr5, text="Delete", command=delete, pady=13)
            buttons[i+1].grid(row=i, column=0, sticky='we')

            i = i + 1

如何获取程序运行时我放在的按钮的索引?

【问题讨论】:

    标签: python arrays user-interface button tkinter


    【解决方案1】:

    您可以将参数传递给您用作命令的函数。

    示例:

    def myButttonCommand(index):
    
       print("this is the "+index+"th' button")
    
    buttons = []
    
    for i in range (0,10):
    
       buttons[i] = tk.Button(command=myButtonCommand(i))
    

    【讨论】:

    • 您发布的代码将不起作用。创建按钮时会立即调用该命令。
    • 我可以保证这行不通。 myButtonCommand(i)立即调用该函数。
    • 也许第一条评论是正确的我做错了什么?
    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 2016-02-21
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2016-03-25
    • 2013-09-29
    • 2017-03-13
    相关资源
    最近更新 更多