/ / Python - Ak príkaz nefunguje vo funkcii def () - python, príkaz if

Python - Ak príkaz nefunguje vo funkcii def () - python, if-Statement

Dúfam, že mi niekto pomôže s týmto problémom.

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()

Používateľ má rozbaľovací zoznam a vyberie 1 preDToB a 2 pre BToD je program schopný identifikovať číslo, ktoré si používateľ vybral, a ja som to skontroloval vytlačením užívateľského vstupu. Tiež som skontroloval a je to str hodnota, ktorá pochádza z tohto rozbaľovacieho zoznamu. Potvrdil som to pridaním userinput do userinput, ktorý mi dal 1 1 namiesto 2, ak to bol int.

Problém je s príkazom if „if userinput ==„ 1 ““ vo funkcii getinput (), ktorý aj keď userinput robí = 1, ide iba o to, čo je v inej časti príkazu.

Predtým som použil výrazy if vo veľmi podobných kódoch, takže nemôžem pochopiť, čo som urobil zle.

Tu je niekoľko obrázkov spusteného programu pic1 pic2

odpovede:

2 pre odpoveď č. 1

Problémom je tento riadok:

choice = OptionMenu(window, variable, "1  ", "2  ")

Keď používateľ zvolí 1, hodnota StringVar je skutočne nastavená "1 ", nie "1". Buď zmeňte hodnoty ponuky možností, alebo zmeňte if userinput == "1" na if userinput = "1 "a váš kód sa bude správať podľa očakávania.