【问题标题】:How to make the if statement function properly?如何使 if 语句正常运行?
【发布时间】:2013-09-26 11:14:17
【问题描述】:

if 语句不起作用。即使您输入正确的值,它也会直接进入 else 并打印不正确。它会直接转到 else 并打印不正确的唯一原因是值不等于条件中的值。

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

【问题讨论】:

  • 嗯,让我们看看。 Python 自 90 年代初就已经存在,被谷歌、ILM 和美国国家航空航天局等主要公司或组织广泛使用,并且是大多数(如果不是全部)Linux 发行版的关键组件......你真的认为if语句可能被破坏?
  • 我的意思是我创建的 if 语句。当然,正确编码的 if 语句应该可以正常运行,但至于我的,它有一些问题。

标签: python user-interface if-statement tkinter


【解决方案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

【讨论】:

  • 我是否必须这样做:如果 float(x_data == 0.25)
  • 您将使用x_data = float(x.get() 将检索到的值转换为float
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
相关资源
最近更新 更多