单击时在网格中获取 tkinter 按钮的行 [英] Getting the row of a tkinter button in grid on click
问题描述
我正在编写一个简单的 tkinter 小部件
,其中有一列输入框和一列按钮.该按钮应在相应的输入框中打印值.我基本上已经编写了所有代码,但我已将行标签硬编码到我的函数中:
I am writing a simple tkinter widget
which a column of entry boxes and a column of buttons. The button should print the value in the corresponding entry box. I have essentially written all the code, but I have hardcoded the row label into my function:
print find_in_grid(root, 2, 0).get()
我需要将 2
替换为被点击的按钮所在的行.我怎样才能得到那一行?
I need to instead replace the 2
with the row of the button that was clicked. How can I get that row?
完整代码:
from Tkinter import *
def print_value():
print find_in_grid(root, 2, 0).get()
def find_in_grid(frame, row, column):
for children in frame.children.values():
info = children.grid_info()
#note that rows and column numbers are stored as string
if info['row'] == str(row) and info['column'] == str(column):
return children
return None
root = Tk()
height = 5
width = 1
for i in range(height): #Rows
for j in range(width): #Columns
b = Entry(root, text="", width=100)
b.grid(row=i, column=j)
height = 5
width = 1
for i in range(height): #Rows
for j in range(width): #Columns
b = Button(root, text="print value", command=print_value, width=10)
b.grid(row=i, column=j+1)
mainloop()
推荐答案
您可以将行和列值作为参数传递给 print_value
.绑定时不要忘记使用默认变量技巧命令,否则它会一直认为你点击了右下角的按钮.
You could pass the row and column values as arguments to print_value
. Don't forget to use the default variable trick when binding the command, or else it will always think you clicked the bottom-right button.
def print_value(row, col):
print find_in_grid(root, row, col).get()
#...
height = 5
width = 1
for i in range(height): #Rows
for j in range(width): #Columns
b = Button(root, text="print value", command=lambda i=i,j=j: print_value(i,j), width=10)
b.grid(row=i, column=j+1)
<小时>
你也可以直接传入入口对象,但这需要一些重构:
You could also pass in the entry objects directly, but this requires some refactoring:
from Tkinter import *
def print_value(entry):
print entry.get()
root = Tk()
height = 5
width = 1
for i in range(height): #Rows
for j in range(width): #Columns
entry = Entry(root, text="", width=100)
entry.grid(row=i, column=j)
b = Button(root, text="print value", command= lambda entry=entry: print_value(entry), width=10)
b.grid(row=i, column=j+1)
mainloop()
这篇关于单击时在网格中获取 tkinter 按钮的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!