Python 3: Tkinter: How to change Entry.get() into an integer

こ雲淡風輕ζ 提交于 2019-12-05 12:35:53

The problem, and what the error states, is that the empty string '' cannot be converted to an integer.

In fact, a lot of strings cannot be converted to an integer. In your case, int(e.get()) raises an error because the entry is empty, but int('') raises an error. Therefore, you need to validate your input before converting it, so as to process it only when it contains the string representation of an integer.

You can wrap a try-except in a get_value function:

def get_value(entryWidget):
    value = entryWidget.get()
    try:
        return int(value)
    except ValueError:
        return None

Then, instead of setting lambda: print(e.get()) as a callback to your button, pass lambda: print(get_value(e)). If the value could be parsed as an integer, this will print the result of int(e.get()). If it couldn't, this will print None.


Here is the modified version of your code:

import tkinter
root= tkinter.Tk()

def get_value(entryWidget):
    value = entryWidget.get()
    try:
        return int(value)
    except ValueError:
        return None


e = tkinter.Entry(root)
e.pack()

b = tkinter.Button(root, command=lambda: print(e.get()))
b.pack()

conversion = get_value(e)
if conversion is not None:
    conversion *= 1.8 + 32
l = tkinter.Label(root, text=conversion)

top.mainloop()

This, however, is a bit awkward. Since the content of the entry is caught before the main loop, the latter will always be empty.

When dealing with GUIs, you cannot think sequencially as you usually do. You should rather ask your button to update the content of your label when pressed, so as to have it display the result of the conversion:

import tkinter


def get_value(entryWidget):
    value = entryWidget.get()
    try:
        return int(value)
    except ValueError:
        return None

def convert(value):
    if value is None:
        return None
    else:
        return 1.8*value + 32

def set_label_text(label, entry):
    value = convert(get_value(entry))
    if value is None:
        label['text'] = "Enter an integer"
    else:
        label['text'] = value


root = tkinter.Tk()

e = tkinter.Entry(root)    
l = tkinter.Label(root, text="")
b = tkinter.Button(root, text="Convert", command=lambda: set_label_text(l, e))

e.pack()
l.pack()
b.pack()

root.mainloop()

Try this code:

import sys

if sys.version_info.major < 3:  # for Python 2.x
    import Tkinter as tk
else:  # for Python 3.x
    import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master.title("Conversion application")
        self.master.geometry("300x100")
        self.x = tk.IntVar()
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.e = tk.Entry(self, textvariable=self.x)
        self.e.bind('<Return>', self.convert)
        self.e.focus()
        self.e.grid()
        self.b = tk.Button(self, text="Convert", command=self.convert)
        self.b.grid()
        self.l = tk.Label(self)
        self.l.grid()

    def convert(self, event=None):
        try:
            print(self.x.get())
            conversion = self.x.get()
            conversion = conversion * 1.8 + 32
            self.l.config(text=conversion)
        except tk.TclError:
            self.l.config(text="Not an integer")

app = Application()
app.mainloop()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!