2013-10-05 71 views
0

如果我創建一個輸入框,如下所示:如何讓用戶在輸入框中輸入浮點數?

myentry = Entry() 
myentry.place (x = 54,y = 104) 

用戶輸入的值是一個字符串值。我必須添加什麼才能使條目成爲浮點數?我試圖寫入「浮動」旁邊的入口括號,但它沒有工作,並告訴我一個錯誤,說tk()不支持浮動。任何幫助,將不勝感激!

+0

使用'v = StringVar()',然後使用'Entry(parent,textvariable = v)'。然後你可以使用'float(v.get())'得到變量爲float。 – SzieberthAdam

回答

0

我寫了一個簡單的腳本來演示如何做你想要的:

from Tkinter import Tk, Button, Entry, END 

root = Tk() 

def click(): 
    """Handle button click""" 

    # Get the input 
    val = myentry.get() 

    try: 
     # Try to make it a float 
     val = float(val) 
     print val 
    except ValueError: 
     # Print this if the input cannot be made a float 
     print "Bad input" 

    # Clear the entrybox 
    myentry.delete(0, END) 

# Made this to demonstrate 
Button(text="Print input", command=click).grid() 

myentry = Entry() 
myentry.grid() 

root.mainloop() 

當你點擊按鈕,程序試圖使在entrybox一個浮動的文本。如果不能,則會打印「錯誤輸入」。否則,它將打印終端中的浮點數。

+0

我試過它,但因爲我是一個初學者,你能解釋我什麼「嘗試:」是和「除了」是因爲從未見過它,你的代碼是什麼:myentry.delete(0,END)是什麼意思? –

+0

因爲我沒有進入它的線,它完美的工作!謝謝 –

+0

@ShahidIqbal - 點擊按鈕後,所有'myentry.delete(0,END)'都會清除輸入框。它基本上是說「從字符位置0到結尾刪除輸入框中的所有文本」。你是對的 - 這不是_必須的。我只是爲了方便而放在那裏。 – iCodez