Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

python - OptionMenu command function requires argument

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...