【发布时间】:2021-06-02 15:07:39
【问题描述】:
嘿,每个人都摸不着头脑,试图弄清楚我的代码出了什么问题,它没有返回任何错误,它似乎只是跳过了计算部分并打印了我包含的错误消息以指示错误的用户输入,即使我的用户输入是有效的。
我尝试移动有关变量的 if 和定义语句,看看是否可行。
我知道变量首先定义在计算函数之上,然后又在函数中定义,我之所以这样做是因为否则我会得到一个错误,即它们是未定义的,除非它们首先出现在其他所有事物之上。
#Weight Converter Calculator with GUI
import PySimpleGUI as sg
def h():
h = height
def g():
g = diameter
if g == 9:
diameter = .7
if g == 11:
diameter == .4
if g == 11.5:
diameter = .38
def u():
u = typeunit
if u == ft:
typeunit = 1
if u == rl:
typeunit = 50
if u == pl:
typeunit = 450
def a():
a = amount
def calc_weight(h, g, u, a):
try:
h, g, u, a = float(h), float(g), float(u), float(a)
h = height
a = amount
g = diameter
u = typeunit
if g == 9:
g = .7
if g == 11:
g = .4
if g == 11.5:
g = .38
if u == 'ft':
u = 1
if u == 'rl':
u = 50
if u == 'pl':
u = 450
weight = h * g * u * a
if weight >= 47001:
standard = 'too heavy for a truck! '
elif weight <= 47000:
standard = 'will fit onto a truck! '
except (ValueError, ZeroDivisionError):
return None
else:
return f'Weight: {weight}, {standard}'
layout = [
[sg.Text('Please enter your desired Mesh Height, Gauge, Unit, Amount')],
[sg.Text('Mesh Height in FT', size =(15, 1)), sg.Input(key = h)],
[sg.Text('Gauge 9, 11, 11.5', size =(15, 1)), sg.Input(key = g)],
[sg.Text('Unit "ft" for sq ft, "rl" for roll, and "pl" for pallet', size =(15, 3)), sg.Input(key = u)],
[sg.Text('Amount', size =(15, 1)), sg.Input(key = a)],
[sg.Text('', key='weight', size=(20, 2))],
[sg.Submit(), sg.Cancel()]
]
window = sg.Window('Chain Link Weight Calculator', layout)
sg.theme('DarkAmber')
while True:
event, value = window.Read()
if event == 'Submit':
weight = calc_weight(value[h], value[g], value[u], value[a],)
if weight:
window.Element('weight').Update(weight, text_color='white')
else:
window.Element('weight').Update('Input is incorrect! ', text_color='red')
elif event == 'Cancel':
break
window.Close()
【问题讨论】:
-
您的
calc_weight功能是否独立工作?我的意思是,给定函数的一组有效输入,它会产生预期的结果吗? -
由于原始
calc_weight使用simplegui 中的value[]键,我将如何使用用户输入单独测试该功能?而且您可能是对的,这很可能是实际功能@itprorh66 的问题:p -
我将首先单独测试函数,并为其提供一系列有效输入值以及一些无效值,以确保函数正确计算。如果该函数正常工作,那么您可以专注于 value[] 函数,以确保它能够满足您的需求。
标签: python-3.x calculator pysimplegui