OptionMenu 命令函数需要参数 [英] OptionMenu command function requires argument

查看:35
本文介绍了OptionMenu 命令函数需要参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于 tkinter 中选项菜单小部件的非常普遍的问题.

This is a pretty general question about the optionmenu widget in tkinter.

当定义一个 OptionMenu 小部件并指定一个函数作为它的命令时,为什么它需要一个参数?

When defining an OptionMenu widget, and assigning a function as its command, why does it require an argument?

我的代码:

from tkinter import *

def update():
    x = optionvar.get()
    x = str(x)
    mylabel.config(text=x)

root = Tk()

l = []
for n in range(10):
    l.append(n)

t = tuple(l)

optionvar = IntVar()

optionvar.set('hello stackoverflow')

mymenu  = OptionMenu(root, optionvar, *t, command=update)
mylabel = Label(root)

mymenu.pack()
mylabel.pack()

我的错误:

TypeError: update() takes 0 positional arguments but 1 was given

简单地定义更新

def update(foo):

似乎有效.但为什么?

推荐答案

回调通常想知道哪个项目被选中,因此 IntVar 的值作为参数传递.如果您想忽略该参数,您可以简单地使用 lambda(_ 是一个有效名称,通常用于表示它是一个一次性变量):

The callback usually wants to know which item was selected, so the value of the IntVar is passed as an argument. If you want to ignore that argument, you can simply use a lambda (_ is a valid name that is commonly used to indicate that it is a throwaway variable):

mymenu = OptionMenu(root, optionvar, *t, command=lambda _: update())

这篇关于OptionMenu 命令函数需要参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆