簡體   English   中英

Python-If語句在def()函數中不起作用

[英]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語句,所以我無法理解自己做錯了什么。

這是運行程序pic1 pic2的一些圖片

問題是這一行:

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

當用戶選擇1時, StringVar的值實際上設置為"1 "而不是"1" 更改選項菜單的值,或者將if userinput == "1"更改為if userinput = "1 " ,您的代碼將按預期運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM