【发布时间】:2021-05-14 16:08:05
【问题描述】:
您好,我是 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, column=1, 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()
【问题讨论】:
-
只定义一个普通的python函数。它将使您的代码更具可读性/可调试性。
-
@TheLizzard 但使用普通函数我无法在按钮命令中分配参数,这就是我使用 lambda 的原因。
-
当然可以。定义
def foo(test): ...,然后使用Button(root, text="...", command=foo)。 -
如果你创建一个合适的函数而不是把代码塞进一个复杂的 lambda 中,你的代码会更容易编写、阅读和管理。
-
按钮的
command选项的回调应该没有参数,所以你的lambda(带有test参数)应该会导致错误。
标签: python tkinter lambda messagebox