社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python 3.7+tkinter:如何确保从文件中为按钮分配了一个单独的函数?

Bart_S • 7 年前 • 1926 次点击  

我最近在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")

问题是:这些按钮显示出各自的颜色和文本,但单击时似乎都会打印出相同的profilename,即列表中最后一个json文件中的profilename。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40604
文章 [ 2 ]  |  最新文章 7 年前
Mike - SMT
Reply   •   1 楼
Mike - SMT    7 年前

我想问题是 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()

结果:

enter image description here

Sun Bear
Reply   •   2 楼
Sun Bear    7 年前

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

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")