【发布时间】:2019-12-12 21:56:20
【问题描述】:
我正在使用 tkinter,因为我已经设置了我的 gui 和条目、标签和按钮。我正在尝试使用用户输入的条目来搜索我的字典键,并打印键入的键的值。例如。
d = {"A":1, "B":2, "C":3}
用户在条目中输入 B 按下按钮,如果 input == "B" 则将 2 打印到标签,否则打印“不匹配”
至少是这样的想法。
我可以查看用户输入是否在字典中,并将一些字符串打印到标签,但不能打印输入到条目中的键的值。
我刚开始用 python 编程并练习。我在这个问题上搜索了大约两天,只能找到基本上跳过 if 语句并直接进入 else 的循环。或者如果条目是“A”,它会打印值 3。我认为这是某种反向字典。所以我试着自己弄清楚。如果我走在正确的轨道上,那就太好了,哈哈,但如果我完全错了..
所以我尝试了普通的 if else 语句、for 循环和使用字典的方法。
d = {"AA":1, "BB":2, "CC":3}
def btn_Clicked():
x = txt.get()
if x in d.keys():
decision.configure(text = "Your value, " + "this is where I'm lost, I'd like it to print the value of that specific key)
else:
decision.configure(text = "No key found")
btn = ttk.Button(win, text = "Find value", command = btn_clicked)
btn.grid(column = 2, row = 0)
txt = ttk.Entry(win, width = 10)
txt.grid(column = 1, row = 0)
position_entry = ttk.Label(win, text= "Enter Key", font = ("Arial Bold", 12))
position_entry.grid(column= 0, row = 0 )
decision = ttk.Label(win, text = "", font = ("Arial Bold", 10))
decision.grid(column= 0,row = 1)
我也尝试过类似
if txt.get() == list(d.keys())[0]:
decision.configure(text = "Your Value is " + str(list(d.values())[0])
在该示例中,我得到了相应的值,但它仅适用于我输入的输入,[0]、[1] 等字典中的项目。
没有错误消息,只是没有做我想做的事。 如果 entry == 到字典中的键,则将“消息”+该键值打印到标签。
【问题讨论】:
-
你能输入你的实际代码吗?
hand未在任何地方声明。它应该是dict吗? (顺便说一句,最好不要使用dict之类的关键字作为变量名).. -
我很抱歉。 d 是字典变量。并且 hand.keys() 应该替换为 d.keys()
标签: python dictionary for-loop if-statement methods