【问题标题】:How do I make a tkinter button in an list of buttons return its index? [duplicate]如何使按钮列表中的 tkinter 按钮返回其索引? [复制]
【发布时间】:2018-06-10 20:41:43
【问题描述】:

我一般是编码新手(Python 是我的第一语言),我在学习 tkinter 时遇到了这个问题。我的代码如下:

from tkinter import *
window = Tk()

buttons = []

def position(pos):
    print(pos)

for i in range(7):
    buttons.append(Button(window, width = 10, height = 5, bg = "red", command = position(i)).grid(row = 0, column = i))

window.mainloop()

这不起作用。单击该按钮时,我想打印该按钮的索引。我尝试了几种方法来实现这一点,但没有成功。按钮不一定要在列表中,但是第一个按钮必须返回 0,第二个返回 1,第三个返回 2 等等。最简单的方法是什么?

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    看这个:

    from tkinter import *
    
    root = Tk()
    
    files = [] #creates list to replace your actual inputs for troubleshooting purposes
    btn = [] #creates list to store the buttons ins
    
    for i in range(50): #this just popultes a list as a replacement for your actual inputs for troubleshooting purposes
        files.append("Button"+str(i))
    
    for i in range(len(files)): #this says for *counter* in *however many elements there are in the list files*
        #the below line creates a button and stores it in an array we can call later, it will print the value of it's own text by referencing itself from the list that the buttons are stored in
        btn.append(Button(root, text=files[i], command=lambda c=i: print(btn[c].cget("text"))))
        btn[i].pack() #this packs the buttons
    
    root.mainloop()
    

    取自:How can I get the button id when it is clicked?

    【讨论】:

    • 效果很好,但是有没有办法调整该代码以使其返回一个整数,例如button1 会返回 1,button2 会返回 2 等等?对于我正在制作的程序来说,按钮返回浮点值或整数值很重要。感谢您的帮助。
    • 是的,'command' 参数用于此目的。您可以在那里调用该函数,请参阅以下内容:pastebin.com/mQrhpcEk 如果这解决了您的问题,您可以接受它:)
    • 非常感谢完美!
    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多