tkinter中将Entry输入框值转为整数触发ValueError报错如何解决
错误原因
代码执行顺序不符合Tkinter界面程序的运行逻辑,sample_value = int(e.get()) 这行代码在界面初始化阶段就会执行,此时输入框还未接收任何用户输入,e.get() 取到的是空字符串'',空字符串无法被转换为十进制整数,因此抛出ValueError。
修复方案
将读取输入框内容、转换为整数的逻辑移动到计算按钮的点击触发函数onclick内,保证只有用户点击按钮、已经完成输入后才会读取输入框内容。同时可以增加输入合法性校验,避免用户输入非数字内容时程序报错。
修正后完整代码
from tkinter import * root =Tk() root.title("Carbon Emission Calculator") root.geometry("2560x1600") #main title main_title = Label(root, text="Carbon Emissions from Zoom Calls", font="Arial 25").pack(pady=75, padx=0) #defining selections for radio buttons x = IntVar() y = IntVar() #type of call type_of_call = Label(root, text="Number of participants", font="Arial 20").pack(pady = 10) Radiobutton(root,text= "1:1 call", variable= x, value=1).pack() Radiobutton(root,text= "Group call", variable= x, value=2).pack() #call quality call_quality = Label(root, text="Call Quality", font="Arial 20").pack(pady = (40,10)) Radiobutton(root,text= "Default", variable= y, value=1).pack() Radiobutton(root,text= "720p HD", variable= y, value=2).pack() Radiobutton(root,text= "1080p HD", variable= y, value=3).pack() #call duration duration_of_call = Label(root, text="Duration of Call (in hours)", font="Arial 20").pack(pady = (40,10)) e = Entry(root, width = 10) e.pack(pady = (0,40)) #calculations are here #if (x.get() == 1): #if y.get = #submit button! def onclick(): input_content = e.get() # 输入合法性校验 if not input_content.isdigit(): Label(root, text="请输入合法的数字时长").pack() return sample_value = int(input_content) Label(root, text= sample_value).pack() submit_button= Button(root, text="Calculate", command = onclick).pack() root.mainloop()
内容的提问来源于stack exchange,提问作者dallenlee
相关产品推荐
相关产品推荐

