问题描述
我正在创建一个接受用户输入的 GUI 界面。 第一,重量。 第二,速度。
然后,我想根据这些输入进行一些计算。 首先,加速,在下面的脚本中显示为我定义的第一个函数。 第二,力,我利用输入的重量乘以加速度函数。
大多数情况下,我已经完成了界面,但我无法测试这些功能是否可以正常工作,除非我将计算值与字典内容进行了比较。
假设我有一个默认的 dict 信息,如下所示。
1 级:A 力:500
2 级:B 力:300
3 级:C 力:100
问题:
例如,如果我输入 50 表示重量,100 表示速度,然后按下按钮,程序应该会根据这些输入自动计算力。
例如,如果计算出的力为 250...该值属于默认字典中的 2 级:B。 (我怎样才能转到默认字典并检查它们,循环遍历其中键的所有值,直到我的程序确定该值实际上属于这个等级?)
然后,GUI 应该在界面中打印最终输出,在这种情况下,它是 GRADE 2:B。
如何在下面的脚本中添加这些? 任何提示将不胜感激。 这是一个作业,但如果你不想给出真正的代码,我理解这很公平。 我只想知道从哪里开始,从哪里看,以及如何理解代码。
所以,如果你能帮忙,我会很高兴。
这是我到目前为止所做的。
from tkinter import *
from tkinter import ttk
x = []
def cal_acceleration(*args):
try:
# 1/2 and 0.4 default value, get the velocity value
# from below then multiplied by 1/2.
acce=((1/2) * ve.get()) / 0.40
x.append(acce)
except ValueError:
pass
def cal_force(*args):
try:
# multiplied the output of this function to the above function.
force=ma.get() * x
except ValueError:
pass
"""Creating a GUI with the following interface."""
root = Tk()
root.title("what type?")
frame = ttk.Frame(root, padding="5 5 5 5")
frame.grid(column=0, row=0, sticky=(N,S,E,W)) # stick frame to center.
ma = StringVar() # allocate user input weight
v = StringVar() # allocate user input speed
ma_entry = ttk.Entry(frame, width=7,textvariable=m) # entry dialogue for weight
ma_entry.grid(column=1,row=0,sticky=(W,E))
ve_entry = ttk.Entry(frame, width=7, textvariable=v) # entry dialogue for speed
ve_entry.grid(column=1,row=1,sticky=(W,E))
ma_label = ttk.Label(frame, text="how heavy:") # labelling weight
ma_label.grid(column=0, row=0,sticky=E)
velo_label = ttk.Label(frame, text="speed:") # labelling speed
velo_label.grid(column=0, row=1,sticky=E)
# setting the button for GUI. combining two functions using lambda.
find_button = ttk.Button(frame, text="Find", command=lambda[cal_acceleration(),cal_force()])
find_button.grid(column=2,row=0,sticky=W)
root.mainloop()
非常感谢您。
1楼
第一步是修复您现有的代码。 就像现在一样,由于下面解释的几个原因,它无法正常工作,这让我认为您(最近)尚未对其进行测试。
Lambda 调用没有“:”,阻止调用您的函数。
检查您的变量名称,是“v”还是“ve”,是“m”还是“ma”?
调试您的计算函数工作(它没有)。
提示:您的数据必须是正确的类型。 你有 Int,它需要 Float。
提示:您认为将列表相乘有效吗?
然后让它先打印你的数据。 当您知道这是您期望的结果时,您就可以开始在 gui 中显示。