Python: 如何用字符串按名称设置函数参数

Python: How to set function parameters by name with string

我正在制作一个用于使用 tkinter 构建 GUI 应用程序的框架,在我的代码中我有一个场景 class add(widget,params) 创建 tkinter 小部件并将其添加到 Scenes 小部件字典的函数。 但我只能添加一个我为其构建了 add() 函数的小部件,因为不同的小部件具有不同的命名参数。

我将如何创建一个函数,该函数采用 {paramName,value} 形式的字典,然后将其传递给小部件函数

例如

scene.add(button, {'command':Click, "text":"click me"} )

我当前的代码是

import tkinter as tk

class scene():
    def __init__(self, title, width, height):
        self.widgets = {}
        self.title = title
        self.width = width
        self.height = height

    def add(self, name, type, widget, root, params):
        if name in self.widgets.keys():
            return
        else:
            if type == "button":
                width = params[0]
                height = params[1]
                text = params[2]
                self.widgets[name] = [widget(root,width=width, height=height,text=text),params[2:]]

    def get(self,name):
        if name in self.widgets.keys():
            return self.widgets[name][0]

你可以利用setattr。请参见下面的示例,其中我为“通用”字符串定义了一个 if 子句:

from tkinter import Tk, Button

class scene():
    def __init__(self, title, width, height):
        self.widgets = {}
        self.title = title
        self.width = width
        self.height = height

    def add(self, name, type, widget, root, params, attributes={}):
        if name in self.widgets.keys():
            return
        else:
            if type == "button":
                width = params[0]
                height = params[1]
                text = params[2]
                self.widgets[name] = [widget(root,width=width, height=height,text=text),params[2:]]
            elif type == "generic":
                width = params[0]
                height = params[1]
                text = params[2]
                widget_obj = widget(root,width=width, height=height,text=text)
                for key, val in attributes.items():
                    setattr(widget_obj, key, val)
                self.widgets[name]=[widget_obj,params[2:]]

    def get(self,name):
        if name in self.widgets.keys():
            return self.widgets[name][0]

# Create intance of tkinter
root = Tk(className = 'Python Examples - Window 0')
root.geometry("600x700")
root.resizable(0,0)

# Call class
sc=scene("Some title", 100, 100)
sc.add("button_widget", "button", Button, root, [10, 10, "some text"])
sc.add("button_widget2", "generic", Button, root, [10, 10, "some text"], {"command": "click", "text": "click me"})