【问题标题】:Tkinter Python: How to pass more than one argument through a lambda function in an OptionMenuTkinter Python:如何通过 OptionMenu 中的 lambda 函数传递多个参数
【发布时间】:2016-03-03 12:43:11
【问题描述】:

所以当标题建议时,我遇到了在更改选项菜单时我想调用的函数的2个参数。

下面是代码:

OPTIONS = [
        "Fire",
        "Ice",
        "Storm",
        "Life",
        "Myth",
        "Death",
        "Balance"
    ]

    var = StringVar(frame)
    var.set("Select School") # initial value

    option = OptionMenu(frame, var,*OPTIONS,command= lambda frame,var : changeSchool(frame,var))
    option.grid(row=0,column=0,sticky=(N,W))

我做了一些研究,我认为我做的一切都是正确的,但是当我在选项菜单中选择一个选项时出现以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Gunner\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Gunner\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3287, in __call__
self.__callback(self.__value, *args)
TypeError: <lambda>() missing 1 required positional argument: 'var'

我以为我已经将 var 传递给了 changeSchool 函数。

感谢您的帮助!

编辑:这是我的 changeSchool 功能,希望看到它的人:

def changeSchool(frame,school):
    print (school)
    WizTool.schoolType = school
    self.initBT(frame,WizTool.schoolType)
    print (WizTool.schoolType)

编辑:这是整个程序(显示框架如何不在范围内)

from tkinter import *
from tkinter import ttk
from functools import partial
import webbrowser
import pprint

class WizTool:
schoolType = "Fire"


#initialize the GUI
def __init__(self, master):
    content = ttk.Frame(master, padding=(3,3,12,12))
    frame = ttk.LabelFrame(content, borderwidth=5, relief="sunken", width=400, height=400,padding=(3,3,12,12),text = "Blade Tracker")
    content.grid(column=0,row=0,sticky=(N,S,E,W))
    frame.grid(column=0, row=0, columnspan=4, sticky=(N, S, E, W))
    self.master = master
    self.initUI(content)
    self.initBT(frame,WizTool.schoolType)


def initUI(self,frame):
    self.master.title("Bootstrapper")


def changeSchool(frame,school):
    print (school)
    WizTool.schoolType = school
    self.initBT(frame,WizTool.schoolType)
    print (WizTool.schoolType)

def initBT(self,frame,mySchool):
#option menu for selecting school

    OPTIONS = [
        "Fire",
        "Ice",
        "Storm",
        "Life",
        "Myth",
        "Death",
        "Balance"
    ]

    var = StringVar(frame)
    var.set("Select School") # initial value

    option = OptionMenu(frame, var,*OPTIONS,command= lambda frame,var : changeSchool(frame,var))
    option.grid(row=0,column=0,sticky=(N,W))





def main():

root = Tk()
root.geometry("800x500+300+300")
app = WizTool(root)
root.mainloop()

main()

【问题讨论】:

    标签: python lambda tkinter arguments optionmenu


    【解决方案1】:

    OptionMenu 小部件的 command 函数只接受一个参数:selected item

    1. 您在调用command 函数吗?答:没有。
    2. 谁在调用command 函数?答案:python。

    Python 将您指定的函数存储在某处,然后在将来某个时间在您在 OptionsMenu 中进行选择后,python 会调用 command 函数。因此,python 决定将多少个参数传递给command 函数,结果python 用一个参数调用command 函数:

     command(selection)
    
    1. 你怎么知道python用一个参数调用command函数?答:您查看文档。

    2. 如果您在文档中找不到任何描述您需要分配给 command 的函数类型的内容会怎样?答:你测试一下。

    第一:

    ...
    ...
    
    def do_stuff(x):
        print(x)
    
    tk.OptionMenu(
        root, 
        str_var, 
        *OPTIONS,
        command=do_stuff).pack()
    
    ...
    ...
    
    --output:--
    Storm
    

    下一步:

    ...
    ...
    def do_stuff(x, y):
        print(x, y)
    
    tk.OptionMenu(
        root, 
        str_var, 
        *OPTIONS,
        command=do_stuff).pack()
    
    ...
    ...
    
    --output:--
    > TypeError: do_stuff() missing 1 required positional argument: 'y'
    

    有多种方法可以解决这个问题...

    使用 python 的作用域规则:

    import tkinter as tk
    
    OPTIONS = [
            "Fire",
            "Ice",
            "Storm",
            "Life",
            "Myth",
            "Death",
            "Balance"
    ]
    
    root = tk.Tk()
    root.title("Hello")
    root.geometry("300x200+10+100")
    
    frame = [1, 2, 3]
    
    def do_stuff(selection):  
        print(selection, frame)  #frame is visible inside the def.
    
    str_var = tk.StringVar(root)
    str_var.set(OPTIONS[0]) # default value
    
    tk.OptionMenu(
        root, 
        str_var, 
        *OPTIONS,
        command=do_stuff
    ).pack()
    
    root.mainloop()
    

    但是让函数操作全局变量并不是一个好主意,所以你可以...

    使用包装函数:

    import tkinter as tk
    
    OPTIONS = [
            "Fire",
            "Ice",
            "Storm",
            "Life",
            "Myth",
            "Death",
            "Balance"
    ]
    
    root = tk.Tk()
    root.title("Hello")
    root.geometry("300x200+10+100")
    
    def wrapper(other):
        def do_stuff(selection):
            print(selection, other)
    
        return do_stuff
    
    str_var = tk.StringVar(root)
    str_var.set(OPTIONS[0]) # default value
    
    tk.OptionMenu(
        root, 
        str_var, 
        *OPTIONS,
        command=wrapper('xxxx')  #This actually executes wrapper(), and a
                                 #function call in your code is replaced
                                 #by its return value--which happens to 
                                 #be the name of a function that takes one
                                 #argument.  The one arg function name is
                                 #then assigned to command.
    ).pack()
    
    root.mainloop()
    

    为额外的参数变量使用默认值:

    frame = [1, 2, 3]
    
    def do_stuff(selection, other=frame):  #<****HERE****
        print(selection, other)
    
    str_var = tk.StringVar(root)
    str_var.set(OPTIONS[0]) # default value
    
    tk.OptionMenu(
        root, 
        str_var, 
        *OPTIONS,
        command=do_stuff
    ).pack()
    

    警告:参数变量的默认值有其自身的问题。默认值在定义函数时被分配一次。随后,无论您执行多少次函数,默认值都会使用相同的值。这意味着如果默认值是一个列表,并且第一次调用函数时更改了该列表,那么下次调用函数时默认值将是更改后的列表。

    【讨论】:

    • @GunnerStone,当然。请参阅我发布的三个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2019-08-25
    相关资源
    最近更新 更多