[英]Python - If Statement With input() Not Functioning Inside def() Function
[英]Python - If statement not functioning inside def() function
我希望有人可以帮助我解决这个问题。
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。
问题出在getinput()函数中的if语句“ if userinput ==” 1“”,即使userinput do = 1时,它也只能与语句中else部分的内容保持一致。
之前我曾在类似的代码中使用过if语句,所以我无法理解自己做错了什么。
问题是这一行:
choice = OptionMenu(window, variable, "1 ", "2 ")
当用户选择1时, StringVar
的值实际上设置为"1 "
而不是"1"
。 更改选项菜单的值,或者将if userinput == "1"
更改为if userinput = "1 "
,您的代码将按预期运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.