我打算编写用(123)计算一个数字的程序,并向我显示它们的总和。但我想编写一个代码,按下(总和)按钮时执行此操作:{如果字段没有任何整数类型的数字调用errorMsg函数,否则计算数字}但我不知道我怎么能知道做这个。请帮忙!
from tkinter import *
frame = Tk()
def textBoxes():
global e1
e1 = Entry(frame,justify=LEFT )
def labels():
var1 = StringVar()
var1.set("Enter first number: ")
label1 = Label(frame, textvariable = var1)
var3=StringVar()
def errorMsg():
msg = messagebox.showinfo("Please Enter Some Number!")
def calculator():
#def __init__(self,String_value1,String_value2,sum_result)
String_value1 = e1.get()
Int_value1 = int(String_value1)
if not(String_value1.get()):
errorMsg()
else:
sum_result = Int_value1 + 123
def buttons():
B1 = Button(frame, text="Sum", command=calculator)
buttons()
labels()
textBoxes()
frame.mainloop()
答案 0 :(得分:0)
在您的计算器方法中,不要检查它是否为空,尝试操作您的值并在失败时捕获异常。它被称为Easier to ask for forgiveness than permission。
result = StringVar()
def calculator():
try:
user_input = int(e1.get())
result.set(str(user_input+123)) #or however you like to show this
except ValueError:
errorMsg()
使用您的代码的小片段:
import tkinter as tk
from tkinter import messagebox
frame = tk.Tk()
var1 = tk.StringVar()
var3 = tk.StringVar()
ent1 = tk.Entry(frame,justify="left")
var1.set("Enter first number: ")
var3.set("Result")
def textBoxes():
ent1.pack()
def labels():
tk.Label(frame, textvariable=var3).pack()
tk.Label(frame, textvariable=var1).pack()
def errorMsg():
messagebox.showinfo("Error", "Please enter a valid number!")
def calculator():
try:
user_input = int(ent1.get())
var3.set("Result = "+str(user_input+123))
except ValueError:
var3.set("Please enter a valid number!")
errorMsg()
def buttons():
tk.Button(frame, text="Sum", command=calculator).pack()
labels()
textBoxes()
buttons()
frame.mainloop()