首页 > 解决方案 > 如何在 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()

标签: pythontkintersequencetkinter-entry

解决方案


考虑这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

推荐阅读