我想问题是
command=print(self.loadeddata.get("profilename"))
类似于lambda语句的问题(也就是说,我很惊讶您的按钮可以工作,它们应该在
init
之后就再也不工作了,因为您是在创建按钮时调用print,而不是将引用保存到print)。
由于lambda在这样一个循环中工作的性质,您最终只能为所有命令打印循环中的最后一个值。相反,您需要使用lambda语句并在lambda for each循环中定义值,以便准确地记录print语句的正确数据。\
我为此创建了3个测试文件:
test.json
:
{"profilename":"test", "profilecolor": "green"}
test2.json
:
{"profilename":"test2", "profilecolor": "blue"}
test3.json
:
{"profilename":"test3", "profilecolor": "orange"}
示例代码:
import tkinter as tk
import json
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.btn_list = []
for file in ['test.json', 'test2.json', 'test3.json']:
with open(file, 'r') as f:
self.btn_list.append(json.load(f))
self.create_tags()
def create_tags(self):
for item in self.btn_list:
tk.Button(self, text=item.get("profilename"), background=item.get("profilecolor"),
command=lambda x=item.get("profilename"): print(x)).pack(side="top", fill="x")
if __name__ == '__main__':
Window().mainloop()
结果: