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

2024-09-30 08:29:44 发布

您现在位置: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: ''
>>> 

我认为可能有一种特殊的方法可以将条目小部件的内容转换为整数,但我不知道为什么(条目小部件的内容默认为字符串)


Tags: from内容title部件方式checker条目place
1条回答
网友
1楼 · 发布于 2024-09-30 08:29:44

例如,您应该仅在用户按下按钮时转换条目的内容

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

相关问题 更多 >

    热门问题