【问题标题】:How to cast string to integer in Tkinter python如何在 Tkinter python 中将字符串转换为整数
【发布时间】:2021-11-12 19:52:57
【问题描述】:

如何在 Tkinter 中将输入框中的字符串转换为整数。 这个我试过了,还是不行。

import tkinter 
from tkinter import tt

age= tkinter.Label(window, text = "How old are you?")
age.grid(row = 1, column = 0)

entry_age = tkinter.Entry(window)
Entry.grid(row = 1, column = 1)

height = tkinter.Label(window, text = "What is your height(cm): ")
height.grid(row = 2, column = 0)

entry_height = tkinter.Entry(window)
entry_height.grid(row = 2, column = 1)

weight = tkinter.Label(window, text = "your weight (kg): ")
weight.grid(row = 3, column = 0)

entry_weight = tkinter.Entry(window)
entry_weight.grid(row = 3, column = 1) 

entry_age1 = entry_age.get()

entry_age1 = int(entry_age1)


entry_heigh1t = entry_height.get()

entry_height1 = int(entry_height1)

entry_weight1 = entry_weight.get()

entry_weight1 = int(entry_weight1)

【问题讨论】:

  • 你的错误是什么?
  • entry_heigh1t = entry_height.get() 我在代码中没有看到任何逻辑错误,但这里有拼写错误
  • 您必须等到用户输入数据后才能进行转换。创建小部件后,您将在大约毫秒内获取条目小部件的内容。

标签: python string tkinter casting integer


【解决方案1】:

请发布您遇到的错误消息以及一些测试用例作为输入框的输入。

entry_age.get() 返回一个字符串,如果输入是数字当然可以使用 int() 转换为整数。

在@Milena Pavlovic 回复错误后编辑:

程序不会运行,因为一旦它运行将空字符串存储到变量中的语句entry_age1 = entry_age.get(),接下来的下一条语句就会尝试将这个空字符串转换为整数。空字符串以“”开头,不能转换为整数类型。由于这是无效的,因此会引发值错误。要解决此问题,您可以进行以下更改:

if entry_age.get().isdecimal():
    entry_age1 = int(entry_age1)

if entry_height.get().isdecimal():
    entry_height1 = int(entry_height1)

if entry_weight.get().isdecimal():
    entry_weight1 = int(entry_weight1)

isdecimal() 函数检查 get() 返回的字符串是否为小数,然后才将其转换为整数并存储到相应的变量中,并允许您对它们做您想做的事情。

【讨论】:

  • 是的;该错误可能是因为您在条目中有任何值之前转换为 int 。因此,您尝试将空 str 转换为 int,而 int() 函数不允许这样做。
  • 我无法运行程序并在“输入”框中输入任何内容,因为它显示以下错误:ValueError: invalid literal for int() with base 10: ''
  • @MilenaPavlovic 请参考编辑后的答案。希望它现在得到解决。
  • 非常感谢。现在我有另一个问题。当我尝试在公式中应用该数据时,它向我显示以下错误:TypeError:无法将序列乘以“浮点”类型的非整数。这是我的代码: def basal_metabolism(): print (447.593 + (9.247 * entry_weight1) + (3.098 * entry_height1 * 100)- (4.330 * entry_age1))
  • @MilenaPavlovic 这是因为您仍在尝试将字符串值与整数值相乘。请再次参考修改后的代码。
【解决方案2】:

这里的 .get() 函数总是将任何内容作为字符串返回。您必须将其转换为 str 到 int。

这是一个简单的例子。

import tkinter as tk

win = tk.Tk()

def get_number():
    text = ent.get()
    try:
        num = int(text)    # <= Focus here
        print(num)
    except:
        print("This is not number")

ent = tk.Entry(win)
ent.grid(row=0, column=0, padx=10, pady=10)

btn = tk.Button(win, text="Get Number", command=get_number)
btn.grid(row=1, column=0)

win.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2010-10-31
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多