我像这样通过循环创建了Entry和按钮
for i in range(len(headers)):
pos_y = 0;
e = tk.Entry(top, width = 30);
e.grid(row = pos_x, column = pos_y);
entry[i] = e;
e.insert(0, headers[pos_x].get('name'));
pos_y += 1;
b = tk.Button(top, text = 'Copy');
b.grid(row = pos_x, column = pos_y);
button[i] = b;
pos_y += 1;
我分别对Entry和Button有两个字典,输出是这样的。 Output
我要为每个按钮做一个操作,我想将值从文本框复制到剪贴板。 我知道如何复制到剪贴板,只是得到相应的值是问题。 编辑: 标头是词典列表; pos_x用于从一行切换到另一行; pos_y用于切换到下一个同伴。 在这里,我在字典上进行迭代,以从dict到第一个文本框获取名称,并从另一个值获取值。 像这样:{“ name”:“ key”,“ value”:“ 2500”} button和entry是字典,在上面被声明为entry {}和button {}。
答案 0 :(得分:0)
我认为您正在使事情变得比他们需要的复杂。您无需将按钮放在dict /列表中,因为创建按钮后无需更改它们。 而是考虑使用一个简单的列表来说明您的输入值,然后在需要时使用它们的索引对它们调用get方法。
这是我的例子。如果您有任何问题,请告诉我。
import tkinter as tk
class Example(tk.Tk):
def __init__(self):
super().__init__()
self.entry_list = []
r = 0
c = 0
for i in range(6):
self.entry_list.append(tk.Entry(self, width=30))
self.entry_list[-1].grid(row=r, column=c)
tk.Button(self, text='Copy', command=lambda ndex=i: self.copy_to_clipboard(ndex)).grid(row=r, column=c+1)
if r == 2:
c += 2
r = 0
else:
r += 1
def copy_to_clipboard(self, ndex):
print(self.entry_list[ndex].get())
self.clipboard_clear()
self.clipboard_append(self.entry_list[ndex].get())
Example().mainloop()
结果:
答案 1 :(得分:0)
您只需将条目引用传递给相应按钮的命令功能,如下所示:
def do_clipboard_copy(entry):
text = entry.get() # get the entry content
print(text)
# do whatever you know to copy the entry content to clipboard
for i in range(len(headers)):
row = i // 2
col = (i % 2) * 2
entry = Entry(top, width=30)
entry.grid(row=row, column=col)
entry.insert(0, headers[i].get('name'))
Button(top, text='Copy', command=lambda e=entry: do_clipboard_copy(e)).grid(row=row, column=col+1)