Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int() can't convert non-string with explicit base when converting to GUI

I was running a basic hex2dec converter, and wanted to transform this from console to GUI.

Now the program works fine in console, but after my conversion to GUI, it seems to throw out the int() can't convert non-string with explicit base error.

Here is the GUI code

from tkinter import *

root = Tk()
root.geometry("400x400+250+250")
root.title("Hex Converter")

heading = Label(root, text="Simple Hex to Decimal Converter", font=('arial 15 bold'), fg="steelblue").pack()

entr_hex_val = Label(root, text="Enter Hex Value to Convert", font=('arial 13 bold')).place(x=10, y=50)

my_num = IntVar()
ent_box = Entry(root, width=50, textvariable=my_num).place(x=10, y=90)

def converter():
    hexdec = my_num.get()
    dec = int(hexdec, 16)
    lab = Label(root, text=("decimal value = "+ str(dec)), font=('arial 25 bold'), fg="red").place(x=10, y=200)

conv = Button(root, text="Convert", width=12, height=2, bg="lightgreen", command=converter).place(x=10, y=130)

root.mainloop()

and the console code

import os

def hexconverter:
    os.system('cls')
    hexdec = input("Enter number in Hexadecimal Format: ")
    dec = int(hexdec, 16)
    print(str(dec))

hexconverter()

I'm struggling to see why the same code works in console but not in the GUI.

like image 591
David M Avatar asked Jan 29 '23 13:01

David M


2 Answers

The hex number needs to be a string, and you are defining my_num as an integer. Changing my_num = IntVar() to my_num = StringVar() should fix it.

like image 130
SuperNano Avatar answered Feb 05 '23 18:02

SuperNano


When you use .get() on IntVar it returns an integer and int conversion with specified base works on strings as stated in your error message.

You can convert the value to string before using it.

dec = int(str(hexdec), 16)

But since you are using hex values, your entry might get characters A-F and IntVar would throw an error if it sees any non-integer value while using .get() so it will be easier for you to use StringVar and using try-except for catching errors on conversion.

Another point is, your code will re-create labels on each click and lab will always have the value None. Recreating might lead some memory issues (OK, maybe not in this little one but still it is worth noting). Instead of creating label everytime, you can create it once in global scope then just change its value when needed.

my_num = StringVar()  

lab = Label(root, text="", font='arial 25 bold', fg="red")
lab.place(x=10, y=200) #also notice seperated the place line to avoid NoneType error

def converter():
    hexdec = my_num.get()
    try:
        dec = int(hexdec, 16)
        lab["text"] = "decimal value = "+ str(dec)
    except ValueError:
        lab["text"] = "Error, please enter valid hex value"
like image 33
Lafexlos Avatar answered Feb 05 '23 16:02

Lafexlos