如何解决如何在 tkinter 中使用带有 if-else 语句的 lambda 函数
嗨,我是 Python 和 tkinter 的初学者,我需要使用一个 Button,该按钮根据用户通过 Entry 引入的键向我显示字典中的值。如果引入的键在字典中,该值应该显示在禁用条目中以用于键的描述,如果它不在字典中,它应该显示一个消息框,要求使用不同的键。我在按钮命令中使用了 if-else lambda 函数,但它似乎不起作用,我不知道为什么。
我会把我正在使用的代码放在下面。
from tkinter import *
from tkinter import messageBox
root=Tk()
dictio={1:"one",2:"two"}
test=False
textEntry = StringVar()
def show_description(key,dict,text):
if key in dict.keys():
textEntry.set(text)
else:
test=True
code_entry = Entry(root)
code_entry.grid(row=1,column=1,sticky='nsew')
description_entry = Entry(root,state="disabled",textvariable = textEntry)
description_entry.grid(row=0,sticky='nsew')
show_button = Button(root,text="Mostrar descripción",command=lambda test:show_description(int(code_entry.get()),dictio,dictio[int(code_entry.get())]) if (test==False) else messageBox.showinfo("Info","The number is not in the database"))
show_button.grid(row=0,column=2)
root.mainloop()
解决方法
command
参数需要一个没有位置参数的函数,因此使用 lambda x: <do-something>
会引发错误。在这种情况下,回调期间不需要传递任何参数,因此您应该将事情简化为
def show_description():
key = int(code_entry.get())
if key in dictio:
textEntry.set(dictio[key])
else:
messagebox.showinfo("Info","The number is not in the database")
show_button = Button(root,text="Mostrar descripción",command=show_description)
还有,这样做
dictio[int(code_entry.get())]
在修复没有参数的 lambda 之后,您所做的可能会引发 KeyError
。
from tkinter import *
from tkinter import messagebox
root=Tk()
dictio={1:"one",2:"two"}
test=False
textEntry = StringVar()
display=StringVar()
def show_description():
print(display.get()) #==get the value of the stringvat
x=int(display.get()) #==convert the value to integer
if dictio.get(x)==None:
messagebox.showinfo("Info","The number is not in the database")
else:
textEntry.set(dictio.get(x)) #==get the value of the key from dictio dictionary and set it for description_entry
code_entry = Entry(root,textvariable=display)
display.set("") #==set value as nothing
code_entry.grid(row=1,column=1,sticky='nsew')
description_entry = Entry(root,state="disabled",textvariable = textEntry)
description_entry.grid(row=0,sticky='nsew')
show_button = Button(root,command=show_description)
show_button.grid(row=0,column=2)
root.mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。