简体   繁体   English

如何将 tkinter 条目转换为整数

[英]How do you convert a tkinter entry to an integer

I need to use an entry from a GUI in an equation, and I consistently get errors when attempting to convert it to an integer.我需要在等式中使用 GUI 中的条目,并且在尝试将其转换为整数时总是出现错误。 The variable I'm attempting to convert is marked as "radius."我试图转换的变量被标记为“半径”。

import math
import tkinter as tk

circ = tk.Tk()
circ.title("Circle")
circ.geometry("150x75")

radiusLabel = tk.Label(circ, text = "What is the radius?")
radiusEntry = tk.Entry(circ)

def close_window():
    circ.destroy()

radius = int(radiusEntry)

submit = tk.Button(circ, text = "Submit", command = close_window)

radiusLabel.pack()
radiusEntry.pack()
submit.pack()
circ.mainloop()

class Shape():
    def __init__(self, radius):
        self.circumference = float(2) * float(radius) * float(math.pi)
        self.area = float(math.pi) * float(radius*radius)

    def getArea(self):
        return self.area

    def getPerimeter(self):
        return self.circumference

    def __str__(self):
        return "Area: %s, Circumference: %s" % (self.area, self.circumference)

circle = Shape(radius)
print(circle)

U can try this function, it works for me你可以试试这个功能,它对我有用

def cvtInt(value):
    fnum = []
    newnum = ''
    for i in value:
        ii = int(i)
        fnum.append(ii)
    for i in fnum:
        newnum = newnum + str(i)
    new = int(newnum)
    return new

Three things that will help you with this:可以帮助您解决此问题的三件事:

  1. General tip: when debugging things like this, use print statements to see if you're getting the information you're expecting.一般提示:在调试此类事情时,请使用打印语句查看是否获得了预期的信息。 Does radiusEntry always give you a number? radiusEntry 总是给你一个数字吗? My guess is probably not.我的猜测可能不是。

  2. I believe you should be using radius = int(radiusEntry.get()) to get the input value我相信你应该使用radius = int(radiusEntry.get())来获取输入值

  3. Probably your best bet is performing a check before you cast the radius to an int, and making sure that you're actually trying to convert a number.可能最好的办法是在将半径转换为 ​​int 之前执行检查,并确保您实际上是在尝试转换数字。 If you're trying to convert a letter or a None datatype, that could be causing your error.如果您尝试转换字母或 None 数据类型,这可能会导致您的错误。 You can check for this using the python isnumeric() method for strings.您可以使用字符串的 python isnumeric()方法检查这一点。

Pseudocode for you:给你的伪代码:

If the radius entry is a number,

   convert the radius entry to an int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM