python中如何定义函数的传入参数是option的_Tkinter Python:如何通过OptionMenu中的lambda函数传递多个参数...

OptionMenu小部件的command函数只接受一个参数:selected item。在您正在调用command函数吗?回答:没有

谁在调用command函数?答案:Python。在

Python将您指定的函数存储在某个地方,然后在将来的某个时候,在options菜单中进行选择之后,Python调用command函数。因此python决定它将传递给command函数的参数数量,结果是python使用一个参数调用command函数:command(selection)你怎么知道python用一个参数调用command函数?回答:你检查文件。

如果在文档中找不到描述您需要分配给command的函数类型的任何内容,会发生什么情况?回答:你来测试一下。

第一个:

^{pr2}$

下一步:...

...

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): #

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值