首页 文章

如何根据用户输入在tkinter中传递不同的命令

提问于
浏览
0

我开始学习python,并认为学习tkinter是个好主意 . 我正在做的是一个程序,它将3个数字作为用户输入并用它们计算一些东西,然后打印出一些东西 .

from Tkinter import *
root = Tk()
root.title("Test")
e1 = Entry(root)
e1.pack()
e2 = Entry(root)
e2.pack()
e3 = Entry(root)
e3.pack()
l = Label(root)
l.pack()

def my_function(a,b,c):
    if some condition:
        (calculations)
        l.config(text="Option1")
    else:
        (calculations)
        l.config(text="Option2")

b = Button(root, text="Result", command= lambda: my_function(float(e1.get()),float(e2.get()),float(e3.get())))

我的问题是,如果输入不是数字,我如何设置按钮来打印错误信息?当我尝试在函数内部执行此操作时,我得到了

ValueError: cannot convert string to float

尽管仍然使用shell在shell中打印错误,我设法使其工作

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func
def checknumber():
    if not isinstance(e1.get(),float) or not ...(same for the others):
        l.config(text="Only numbers")
b = Button(root, text="Result", command= combine_funcs(checknumber, lambda: my_function(float(e1.get()),float(e2.get()),float(e3.get()))))

是否有一种更简单的方法可以不给我一个错误?谢谢

1 回答

  • 2

    使用 try-except 指令:

    try:
        # your code
        b = Button(root, text="Result", command= lambda: my_function(float(e1.get()),float(e2.get()),float(e3.get())))
    
    except ValueError:
        # if it catches the exception  ValueError
        b = Button(root, text="Only numbers")
    

    更多关于Exception handling

相关问题