如何将条目小部件(默认情况下具有字符串数据类型)的内容转换为整数?

时间:2019-02-21 18:34:10

标签: python

我试图通过以下方式做到这一点:

from tkinter import*

# creates a GUI
Tester = Tk()

# gives the mainframe a title
Tester.title("")

NonEssentialFoodEntry = Entry(Tester, width="30")

NonEssentialFoodEntry.place(x=300,y=540)

NonEssentialFood = ""

NonEssentialFood = NonEssentialFoodEntry.get()

NonEssentialFood = int(NonEssentialFood)

def checker():
    if NonEssentialFood <0:
        print(' negative number entered')

# assigns attributes to button
Checker=Button(Tester, height="7",width="30",font=300,command=checker)

# displays and places button
Checker.place(x=700, y=580)

    NonEssentialFood = int(NonEssentialFood)
ValueError: invalid literal for int() with base 10: ''
>>> 

我认为可能存在一种将条目小部件的内容转换为整数的特殊方法,但是我不确定为什么。 (输入小部件的内容默认为字符串)。

1 个答案:

答案 0 :(得分:1)

例如,仅当用户按下按钮时,才应转换条目的内容

def checker():
    try:
        user_input = int(NonEssentialFoodEntry.get())
    except ValueError:
        # Deal with non numeric inputs here
    if user_input < 0:
        print('Negative number entered')