简体   繁体   中英

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. 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? My guess is probably not.

  2. I believe you should be using radius = int(radiusEntry.get()) to get the input value

  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. If you're trying to convert a letter or a None datatype, that could be causing your error. You can check for this using the python isnumeric() method for strings.

Pseudocode for you:

If the radius entry is a number,

   convert the radius entry to an int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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