Python 转换为 GUI 时,int() 无法使用显式基数转换非字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46341329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:34:41  来源:igfitidea点击:

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

pythonpython-3.xtkinter

提问by David M

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

我正在运行一个基本的 hex2dec 转换器,并希望将其从控制台转换为 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 baseerror.

现在该程序在控制台中运行良好,但是在我转换为 GUI 之后,它似乎抛出了int() 无法转换具有显式基本错误的非字符串

Here is the GUI code

这是GUI代码

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.

我正在努力了解为什么相同的代码在控制台中有效,但在 GUI 中无效。

回答by SuperNano

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

十六进制数必须是一个字符串,而您定义my_num为一个整数。更改my_num = IntVar()my_num = StringVar()应该修复它。

回答by Lafexlos

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

当您使用它时.get()IntVar它会返回一个整数和 int 转换,其中指定的基数适用于您的错误消息中所述的字符串。

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 IntVarwould throw an error if it sees any non-integer value while using .get()so it will be easier for you to use StringVarand using try-exceptfor catching errors on conversion.

但是由于您使用的是十六进制值,因此您的条目可能会得到字符 AF 并且IntVar如果在使用时看到任何非整数值,则会抛出错误,.get()因此您可以更轻松地使用StringVartry-except用于捕获转换时的错误。

Another point is, your code will re-create labels on each click and labwill 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.

另一点是,您的代码将在每次点击时重新创建标签,并且lab始终具有值None。重新创建可能会导致一些内存问题(好吧,也许不是在这个小问题中,但仍然值得注意)。无需每次都创建标签,您可以在全局范围内创建一次,然后在需要时更改其值。

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"