Python Tkinter开发问题:如何检测两个数组中是否存在相同变量
解决Tkinter 20问游戏的选项判断问题
嘿,我来帮你搞定这个问题!听起来你现在的核心困扰是:不管选哪个选项,失败次数loses都会无脑加1,没法正确识别出那个叫A2的正确选项对吧?这大概率是你的条件判断逻辑出了问题,咱们一步步来捋清楚。
先揪出问题根源
你提到要检测变量是否存在于两个不同数组中,我猜你可能写了类似这样的错误逻辑:
# 错误示例:逻辑运算符用错了! selected_option = var.get() if selected_option not in array1 or selected_option not in array2: loses += 1
这个逻辑的bug在于:A2肯定只在其中一个数组里(假设两个数组只有A2是重叠项),所以selected_option not in array1或者selected_option not in array2永远为真——不管选啥都会触发失败次数增加,完全达不到你要的效果。
正确的实现方案
根据你的需求,我分两种常见场景给你写好正确的逻辑:
场景1:A2是唯一的正确选项
如果只要选中A2就算答对,其他选项都算失败,直接判断选中值是否等于A2就行:
from tkinter import Tk, StringVar, OptionMenu, Button root = Tk() root.title("20问游戏") # 初始化全局变量 loses = 0 score = 0 # 两个选项数组 array1 = ["A1", "A2", "A3", "A4"] array2 = ["B1", "B2", "A2", "B4"] # 绑定菜单选中变量 selected_var = StringVar() selected_var.set(array1[0]) # 设置默认选项 # 创建第一个菜单 menu1 = OptionMenu(root, selected_var, *array1) menu1.pack(pady=10) # 创建第二个菜单(假设和第一个联动,这里简化处理) menu2 = OptionMenu(root, selected_var, *array2) menu2.pack(pady=10) def check_answer(): global loses, score selected = selected_var.get() if selected == "A2": # 答对的逻辑:加分、提示等 score += 1 print(f"答对啦!当前得分:{score}") else: # 答错的逻辑:失败次数加1 loses += 1 print(f"答错了!当前失败次数:{loses}") # 确认按钮 confirm_btn = Button(root, text="确认选择", command=check_answer) confirm_btn.pack(pady=10) root.mainloop()
场景2:需要判断选项是否同时存在于两个数组中
如果你的正确条件是「选中的选项同时在两个数组里」(也就是只有A2符合),那用and运算符来判断:
def check_answer(): global loses, score selected = selected_var.get() if selected in array1 and selected in array2: # 符合条件的正确逻辑 score += 1 print(f"答对啦!当前得分:{score}") else: loses += 1 print(f"答错了!当前失败次数:{loses}")
额外注意事项
- 如果你在函数里修改全局的
loses或score,一定要用global声明,否则会创建局部变量,导致外部的变量值不会更新。 - 确保你正确绑定了OptionMenu的
StringVar,获取选中值时用var.get(),而不是直接操作菜单组件。 - 如果两个菜单是联动的,要保证选中变量是同一个,或者在判断时同时获取两个菜单的选中值进行校验。
内容的提问来源于stack exchange,提问作者thetriplelanguageuser
相关产品推荐
相关产品推荐

