如何将Entry String转换为int或float?

时间:2019-08-03 09:15:28

标签: python tkinter tkinter-entry

如何将Entry字符串转换为数字int或float值

#========================= Imports files and Widgets 
#===================================================================

from tkinter import *

#========================= Main Window Size 
main_window = Tk()
main_window.title("Entry Input Test")

width = 400
height = 200
main_window.geometry(str(width) + "x" + str(height) + "+600+520")
main_frame=Frame(main_window)

################ Varibles 

VarWidthECC = 20

################ Input Boxes 

如何将Entry输入字符串转换为int或float值

First_Value=Label(main_frame,text="Enter First Value ")
First_Value.grid(row=10,column=5, padx=10, sticky=E)
First_Value=(Entry(main_frame, width=VarWidthECC, justify='right'))
#First_Value=Input(main_frame, width=VarWidthECC, justify='right')
First_Value.grid(row=10,column=6, padx=10, pady=0)

Second_Value=Label(main_frame,text="Enter Second Value ")
Second_Value.grid(row=20,column=5, padx=10, sticky=E)
Second_Value=Entry(main_frame, width=VarWidthECC, justify = 'right')
#Second_Value=Input(main_frame, width=VarWidthECC, justify = 'right')
Second_Value.grid(row=20,column=6, padx=20, pady=10)

################ Comparison Function 

def Enter_Button():

    #global First_Value, Second_Value

    print("First Value is: " + First_Value.get())
    print("Second Value is: " + Second_Value.get())
    #value = int(First_Value)
    print(type(First_Value))

如何将Entry字符串转换为数字int或float值

    #Multiply_test = int(First_Value) * 5  #this line of code is Error
    #How can I convert Entry string into int or float??

下面的乘法测试有效         Multiply_test = 6 * 6         print(“ Multiply_test是:” + str(Multiply_test))

################ Run Button ####################################
button_enter = Button(main_frame, width=20, background="light grey", 
text=" Enter ", font="Verdana 10 bold", command=Enter_Button, bd=6, 
relief='raise')
button_enter.grid(row=100, column=6, padx=10, pady=5)

####################################################

main_frame.grid(row=0,column=0)       # Prints out Labels on Main Window
main_window.mainloop()                # Code to End Main Window (root)

2 个答案:

答案 0 :(得分:2)

使用.get()方法以字符串形式给出条目的输入。您正在尝试将tkinter条目转换为float / int,但是忘记使用get方法。

以此替换Enter_Button()并尝试:

def Enter_Button():

    #global First_Value, Second_Value

    print("First Value is: " + First_Value.get())
    print("Second Value is: " + Second_Value.get())
    #value = int(First_Value)
    print(type(First_Value.get()))   #< Use get method as you used it above
    print(type(int(First_Value.get())))
    print(type(float(First_Value.get())))

答案 1 :(得分:0)

.get() 返回一个 str 对象,我们已经知道 python 使用 . 进行浮点识别。

if '.' in First_Value.get():
    # You got an Float
    return float(First_Value.get()) # Never reached to else for TYPE error
else :
    #You got an Integer
    return int(First_Value.get())

实际上这不是一个完整的灵魂,check this .