2013-09-26 143 views
0

if語句不起作用,即使您輸入了正確的值,它也會直接轉到else並打印不正確。它會直接轉到else和print不正確的唯一原因是如果值不等於條件中的值。如何使if語句正常工作?

from Tkinter import * 
import tkMessageBox 

app = Tk() 
# Message Window 

def messagePop(): 
    get_data() 
    tkMessageBox.showinfo('Results', '100% Very Good') 

# Background colour 

app.configure(bg='gray') 



# The position and size relative to the screen 
app.geometry('500x500+450+140') 

# The title of the program 
app.title('Maths4Primary') 

# The icon 
app.wm_iconbitmap('MathIcon.ico') 

# Object positioning in the program 
# def GridPos: 

# I might use the place() method for the screen layout. 
Label(app, text="Put these prices in order", bg="gray", fg="blue").place(x=100,y=10) 

Label(app, text= u"\xA3" + "20.50", bg="gray", fg="blue").place(x=50,y=35) 

Label(app, text=u"\xA3" + "2.50", bg="gray", fg="blue").place(x=200,y=35) 

Label(app, text= u"\xA3" + "0.25", bg="gray", fg="blue").place(x=350,y=35) 

# Entry 






global x_data,y_data,z_data      #----------add this 

def get_data(): 
    global x_data,y_data,z_data 
    x_data = x.get() 
    y_data = y.get() 
    z_data = z.get() 
    print "x_data = {0} , y_data = {1} , z_data = {2}".format(x_data,y_data,z_data) 

def messagePop(): 
    get_data() 
    #---your Entry, which YOU NEED HELP ON THIS PART 
    if (x_data==0.25) and (y_data==2.5) and (z_data==20.5): #----------compare here 
     print("Well done") 
     # tkMessageBox.showinfo('Results', '100% Very Good') 

    else : 
     print ("Incorrect") 










x = Entry(app) 
y = Entry(app) 
z = Entry(app) 

x.place(x=50,y=60) 
y.place(x=200,y=60) 
z.place(x=350,y=60) 

# Buttons 
B1 = Button(app,text='Marks',bg='gray99',fg='black', command = messagePop).place(x=425,y=450) 

app.mainloop() 
+0

嗯,讓我們來看看。 Python自90年代初就已經出現,廣泛用於谷歌,ILM和NASA等大公司或組織,並且是大多數(如果不是全部)Linux發行版的關鍵組件......並且您真的認爲像'if'聲明可能被破壞? –

+0

我的意思是我創建的if語句。當然,一個正確編碼的if語句應該沒有錯誤地發揮作用,但是對於我來說它有一些問題。 –

回答

1

您正在比較字符串與浮點值。他們永遠不會是相同的,因爲他們不是相同的基本類型。

比較字符串:

if x_data == "0.25" and y_data == "2.5" and z_data == "20.5": 

或轉換x_datay_dataz_data第一漂。請注意,浮點數比較也存在問題,因爲浮點數對其精度有限制。例如,請參見floating point equality in Python and in general

+0

我需要做這樣的事情:if float(x_data == 0.25) –

+0

你會使用'x_data = float(x.get()''將檢索值轉換爲'float'。 –