Python 3.7 + tkInter:如何确保为按钮分配了文件中的单个功能?

时间:2019-02-27 14:03:15

标签: python-3.x tkinter

我遇到了一些问题,难以解决最近在python中遇到的问题。

因此,基本上,我想允许用户加载几个json文件,所有文件都列在python列表中。这些文件包含用于创建按钮的参数,这些参数包括按钮应具有的颜色,应在其中显示的文本以及单击后需要执行的命令。

        def createTags(self):
        for items in self.LoadedInstallProfiles:
            with open(items, "r") as jsonfiles:
                self.loadeddata = json.load(jsonfiles)
                self.tag = Button(self.tagmenu, text=self.loadeddata.get("profilename"), background=
                self.loadeddata.get("profilecolor"), command=print(self.loadeddata.get("profilename")))
                self.tag.pack(side="top",fill="x")

问题是:按钮显示时带有各自的颜色和文本,但是在单击时,所有按钮似乎都打印出相同的配置文件名称,即列表中最后一个json文件中的配置文件名称。

2 个答案:

答案 0 :(得分:0)

我常用的方法是将创建的按钮小部件存储在列表中。我已经修改了您的方法。见下文。

def createTags(self):

    # First create the widget and append to list variable 
    self.tags = [] #List to store button widgets
    for items in self.LoadedInstallProfiles:
        with open(items, "r") as jsonfiles:
            loadeddata = json.load(jsonfiles)
            text = loadeddata.get("profilename")
            bg = loadeddata.get("profilecolor")
            tag = Button( self.tagmenu, text=text, background=bg, command=print(text) )
            self.tag.append( tag )

    # Then display the widgets
    for tag in self.tags:
        tag.pack(side="top",fill="x")

答案 1 :(得分:0)

我想象command=print(self.loadeddata.get("profilename"))的问题类似于lambda语句的问题(这让我感到惊讶,您的按钮根本无法工作,它们应该在init上打印一次,然后再也不工作了,因为您在创建按钮时调用了print,而不是保存对打印的引用。

由于lambda在这样的循环中的工作原理,您最终只能为所有命令打印循环中的最后一个值。相反,您需要使用lambda语句,并在lambda中为每个循环定义值,以准确记录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()

结果:

enter image description here