我正在编写一个简单的tkinter widget
,其中包含一列输入框和一列按钮。该按钮应在相应的输入框中打印该值。我基本上编写了所有代码,但是我已经将行标签硬编码到我的函数中:
print find_in_grid(root, 2, 0).get()
我需要将2
替换为单击按钮的行。我怎么能得到那一行?
整个代码:
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()
答案 0 :(得分:3)
您可以将行和列值作为参数传递给print_value
。绑定命令时不要忘记使用default variable trick,否则它总是认为你点击了右下角的按钮。
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)
您也可以直接传入条目对象,但这需要进行一些重构:
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()