OptionMenu command function requires argument

喜夏-厌秋 提交于 2021-01-16 01:08:52

问题


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

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

My code:

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

My errors:

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

Simply defining update with

def update(foo):

seems to work. But why?


回答1:


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


来源:https://stackoverflow.com/questions/35974203/optionmenu-command-function-requires-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!