简体   繁体   English

PySimpleGUI 中的计算器

[英]Calculator in PySimpleGUI

I have a simple calculator with a fixed constant and another entry to be added to the constant.我有一个简单的计算器,它有一个固定常数和另一个要添加到常数的条目。 I am struggling to deal with these entries(VARIABLE) being negative ie -1234 since i cast an int() on the input so clearly this leads to problems when trying to calculate the sum.我正在努力处理这些条目(变量)为负值,即 -1234,因为我在输入上投射了一个 int() 很明显这会导致在尝试计算总和时出现问题。

import PySimpleGUI as sg

columns = ["FIXED","VARIABLE","RESULT"]
param = (20,3) # size of the main window

def CALCULATOR():
    sg.theme('Dark Brown 1')
    listing = [sg.Text(u, size = param) for u in columns]
    core = [
    sg.Input(f"{10}", size = param),
    sg.Input(size = param,enable_events=True,key='NUMBER'),
    sg.Input(size = param)]

    mesh = [[x,y] for (x,y) in list(zip(listing, core))]
    window = sg.Window('CALCULATOR', mesh, font='Courier 12').Finalize()
    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == "SEND":
            break
        elif event == "NUMBER":
            variable = int(values['NUMBER'])
            fixed= int(values[0])
            for element, value in zip(core[2:], [variable+fixed]):
               element.update(value=value)
        else:
            print("OVER")
    window.close()
CALCULATOR()

You can wrap your if-statements in a try-except statement, and then handle the updates for when there is a ValueError :您可以将 if 语句包装在try-except语句中,然后在出现ValueError时处理更新:

while True:
    event, values = window.read()
    try:
        if event == sg.WINDOW_CLOSED:
            break
        elif event == "SEND":
            break
        elif event == "NUMBER":
            variable = int(values['NUMBER'])
            fixed = int(values[0])
            core[2].update(variable+fixed)
        else:
            print("OVER")
    except ValueError:
        core[2].update("ValueError!")

The above code "catches" the ValueError that is triggered once you input something that doesn't translate well into an integer, after that you can then update the field to inform the user why the results didn't output.上面的代码“捕获”一旦您输入不能很好地转换为整数的内容时触发的 ValueError,然后您可以更新该字段以通知用户为什么结果没有输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM