简体   繁体   中英

Python - If statement not functioning inside def() function

I hope someone can help me with this issue.

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

The user has a drop down list, and selects 1 for DToB and 2 for BToD, the program is able to identify the number that the user chose and I checked it does this by printing userinput. I have also checked and it is a str value that comes from this drop down list I confirmed this by adding userinput to userinput which gave me 1 1 instead of 2 if it was an int.

The issue is with the if statement " if userinput =="1" " in the getinput() function which even when userinput does = 1 just goes with what is in the else part of the statement.

I have used if statements like this in very similar codes before so I cannot understand what I have done wrong.

Here is some pictures of the program running pic1 pic2

The problem is this line:

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

When the user chooses 1, the value of the StringVar is actually set to "1 " , not "1" . Either change the values of the option menu or change if userinput == "1" to if userinput = "1 " , and your code will behave as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM