python - 如何在 tkinter 中执行这个简单的计算
问题描述
(这段代码有什么问题?有两个输入字段。我想输入成绩 A 或 B 并将其转换为分数,然后将分数乘以小时以获得最终结果。
如果等级=A+ 并且小时数=4,答案应该是 16。如何做到这一点?)
from tkinter import *
root = Tk()
root.title("Simple Calculatoion")
grade =Entry(root).pack()
hours= Entry(root).pack()
def calculation():
global score
if grade.get()=="A+":
score=4
elif grade.get()== "A":
score = 3.7
label=Label(root, text= score * hours.get() )
label.pack()
button = Button(root, command=calculation, text="Calculate")
button.pack()
root.mainloop()
解决方案
考虑这hours.get()
将返回一个字符串,而不是一个数字。
将字符串与数字相乘通常不起作用。
>>> 3.7*'4'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
如果它确实有效,它不会做你想做的事:
>>> 3*'4'
'444'
试试这个;
def calculation():
scores = {'A+': 4, 'A': 3.7}
score = scores.get(grade.get(), 1)
try:
num = float(hours.get())
except ValueError: # not a valid float
num = 0
# Create the label when you create the other widgets!
# Just set the contents here.
label['text'] = str(score * num)
该scores
词典可以很容易地扩展到其他年级。
请注意,我在get
这里使用字典的方法,因为它处理字典中不存在键的情况。观察:
>>> scores = {'A+': 4, 'A': 3.7}
>>> scores['A']
3.7
>>> scores['V']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'V'
>>> scores.get('V', 42)
42
推荐阅读
- ios - dyld:未加载库:@rpath/GoogleInteractiveMediaAds.framework/GoogleInteractiveMediaAds 自定义框架集成中的错误
- linux - 如何使用 Bash 收缩/收缩一组值
- python - 如何将 django 1.11 移植到 django 2.2 和 python 2.7 到 3.5?
- powerbi - 总和基于值是否在不同的表中可用
- amazon-web-services - 如何使用氡的 JSON 结果在 Athena 中创建表
- linux-kernel - Linux设备树:如何解析包含单元列表的属性
- laravel - 如何更改现有字段类型表的属性
- google-analytics - 我想设置一个目标,以便漏斗也显示用户总数
- webhooks - Integromat - 保存以前参加的人并将新人添加到列表中
- eclipse - 如何将 Apache POI 正确添加到 JSP 以在 Eclipse 中执行 XWPFDocument?