我希望有人可以帮我解决这个问题。
from tkinter import *#This enables me to use the tkinter commands
window=Tk()#This declares the window
window.title("Binary-Denary converters")#This defines the name of the window
loop=1
def selection():
global submitbutton
global variable
global choice#This declares the variable so it can be used anywhere in the code
label1=Label(window,text="Submit 1 for D-B \nSubmit 2 for B-D ")#This tells the user what to input
label1.pack()
variable= StringVar(window)
variable.set("")
choice=OptionMenu(window, variable,"1 ", "2 ")
choice.pack()
submitbutton=Button(window, text="Submit",command=getinput)
submitbutton.pack()
def getinput():
global variable
global userinput
userinput=variable.get()#This takes the users input and assigns it to a variable
print(userinput)
if userinput =="1":
DToB()
else:
BToD()
def DToB():
display1=Label(window, text="D to B")
display1.pack()
submitbutton.destroy()
def BToD():
display2=Label(window, text="B to D ")
display2.pack()
submitbutton.destroy()
selection()
用户有一个下拉列表,并为DToB选择1,为BToD选择2,程序能够识别用户选择的号码,我通过打印userinput检查了它。我也检查了它是来自这个下拉列表的str值我通过向userinput添加userinput来确认这一点,如果它是一个int,它给了我1 1而不是2。
问题在于if语句" if userinput ==" 1" "在getinput()函数中,即使userinput = 1,也只是在语句的else部分中。
我之前在非常相似的代码中使用了if语句,所以我无法理解我做错了什么。
答案 0 :(得分:2)
问题在于这一行:
choice = OptionMenu(window, variable, "1 ", "2 ")
当用户选择1时,StringVar
的值实际上设置为"1 "
,而不是"1"
。更改选项菜单的值或将if userinput == "1"
更改为if userinput = "1 "
,您的代码将按预期运行。