我是一般的编码新手(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,第三个按钮等等。最简单的方法是什么?
答案 0 :(得分:0)
见:
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()