ValueError:即使输入是 int,也无法将字符串从 Entry 转换为 int [英] ValueError: Cannot convert string from Entry to int even though input is int

查看:22
本文介绍了ValueError:即使输入是 int,也无法将字符串从 Entry 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

条目 self.r 的输入为1,12",我正在尝试将其转换为 (1,12) 的元组.方法:tup = tuple(int(x) for x in self.r.split(",")) 适用于普通的 python 程序,但是当与 Entry 的输入一起使用时,它会给出这个错误:

The Entry self.r has input of '1,12', and I'm trying to convert it to a tuple of (1,12). The method: tup = tuple(int(x) for x in self.r.split(",")) works for normal python program, but when used with input from Entry, it gives this Error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1549, in __call__
    return self.func(*args)
  File "/Users/LazyLinh/PycharmProjects/TimeGenGUI/GUI/__init__.py", line 54, in calculateTime
tup = tuple(int(x) for x in self.r.split(","))
  File "/Users/LazyLinh/PycharmProjects/TimeGenGUI/GUI/__init__.py", line 54, in <genexpr>
tup = tuple(int(x) for x in self.r.split(","))
ValueError: invalid literal for int() with base 10: ''

可能是什么问题?这是我的完整代码:

What could the issue be? This is my full code:

from tkinter import *
import math

class TimeGenerator:

    def __init__(self,master):
        frame = Frame(master)
        frame.grid()
        label_iso = Label(root, text="Isotope A, Element")
        label_vol = Label(root, text="Voltage")
        label_range = Label(root, text="Charge Range")

        entry_iso = Entry(root)
        entry_vol = Entry(root)
        entry_range = Entry(root)

        label_iso.grid(row=0, sticky=E)
        label_vol.grid(row=1, sticky=E)
        label_range.grid(row=2, sticky=E)

        entry_iso.grid(row=0, column=1)
        entry_vol.grid(row=1, column=1)
        entry_range.grid(row=2,column=1)

        button = Button(root, text='Time Range', command=self.calculateTime)
        button.grid(row=3, columnspan=2)


        self.iso = entry_iso.get()
        self.vol = entry_vol.get()
        self.r = entry_range.get()

    def calculateTime(self):
        x = 5

        self.iso.replace(" ", "")
        list = []
        for e in self.iso.split(","):
            list.append(e)

        f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
        i = 0
        while (i < 40):
            header = f.readline()
            i += 1

        for line in f:
            line = line.strip()
            columns = line.split()
            if (list[0] == columns[5]):
                if (list[1] == columns[6]):
                    self.mass = float(columns[13]) + float(columns[14])

        self.r.replace(" ", "")
        tup = tuple(int(x) for x in self.r.split(","))

        list = []
        for q in range(tup[0], tup[1] + 1):
            y = x * math.sqrt(self.mass / (2 * q * float(self.vol)))
            list.append(y)
        i = tup[0]
        for time in list:
            print(i, ':', time)
            i = i + 1


root = Tk()
b = TimeGenerator(root)
root.mainloop()

谢谢!!!

推荐答案

这是我以前见过的一个陷阱",你期望这个:

This is a 'gotcha' that I have seen before, where you expect this:

self.r = entry_range.get()

说让 self.r 成为条目的字符串值"但实际上是让 self.r 成为当前 条目的内容",如稍后使用 self.r 时一样,它仍然表示初始化后立即的值(您调用 .get() 的地方)它总是 <代码>''.(空字符串)

To say "let self.r be the string value of the entry" but it is actually "let self.r be the current content of the entry" as in when you use self.r later it still represents the value immediately after initialization (where you called .get()) which is always ''. (an empty string)

解决方案很简单在您需要时获取条目的内容,因此只需引用您的条目而不是 getting 然后立即:

The solution is simply get the content of the entry when you need it so just have a reference to your entries instead of getting then immediately:

    self.iso_entry = entry_iso
    self.vol_entry = entry_vol
    self.r_entry = entry_range

然后,当您要使用条目中的值时,请使用 .get() 方法:

Then when you are going to use the value in the entry you use the .get() method:

iso = self.iso_entry.get().replace(" ", "")
#btw, try not to shadow the name 'list'
list = iso.split(",") #this returns a list, no extra work needed.
...
r = self.r_entry.get().replace(" ","")
tup = tuple(int(x) for x in r.split(","))

另一种方法是改用 properties 以便它在每次使用 self.r确实检索条目的当前值:

Another way is to instead use properties so that it does retrieve the current value of the entry every time you use self.r:

class TimeGenerator:
    @property
    def r(self):
        return self.r_entry.get()
    @property
    def iso(self):
        return self.iso_entry.get()
    @property
    def vol(self):
        return self.vol_entry.get()

然后您可以保留代码原样,使用 self.r 将为您动态获取内容,尽管不要指望这样做会引起任何注意:

Then you can leave the code as it is and using self.r will dynamically get the contents for you, although don't expect this to do anything noticeable:

self.r.replace(" ","")

Python 字符串是不可变的,所以 .replace 方法返回一个 new 字符串,你不做任何事情,如果你想改变它,你通常会这样做:

Python strings are immutable so the .replace method returns a new string that you don't do anything with, if you wanted to change it you would normally do:

 self.r = self.r.replace(" ","")

但是如果没有属性的 setter 这会引发错误,因此您最终可能会使用局部变量:

But without having a setter for the property this raises an error, so you will probably end up using a local variable anyway:

r = self.r.replace(" ","")
tup = tuple(int(x) for x in r.split(","))

这篇关于ValueError:即使输入是 int,也无法将字符串从 Entry 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆