【问题标题】:How to get value from entry (Tkinter), use it in formula and print the result it in label如何从条目(Tkinter)中获取值,在公式中使用它并将结果打印在标签中
【发布时间】:2019-04-18 04:51:45
【问题描述】:

使用Tkinter的函数入口时,可以写一个字符串值,用它做事;但我实际上正在使用公式。这个想法相当简单:放置一堆盒子来填充数字(压力、推力、应力、温度等),然后获取这些数字,应用公式并在同一窗口中显示结果。

我该怎么做?

我一直在寻找几个小时和几个小时,但没有找到一个不令人困惑的解决方案。

似乎这个页面中的人也遇到了同样的问题,但我不明白解决方案的核心:How to get value from entry(Tkinter), use it in formula and print the result it in label

这也是我能得到的少数几个(只有 2 个)的另一个例子,但对我来说,比上面的前一个复杂得多:

https://www.python-course.eu/tkinter_entry_widgets.php

如果有人可以分享一个完整的程序来解释我如何在我未来的项目中应用从字符串条目中获取数值的概念,我会非常高兴。

【问题讨论】:

    标签: python tkinter tkinter-entry


    【解决方案1】:

    您可以通过 .get() 从小部件中获取值

    from tkinter import *
    #Create the window
    myWindow = Tk()
    
    #Define your formula here
    def MyCalculateFunction():
    
        #Get your value from box_pressure
        #Remember to convert string to integer or float / double
        pressure, temprature = float(box_pressure.get()), float(box_temprature.get())
        result = pressure + temprature
    
        #Show your result with label
        label_result.config(text="%f + %f = %f" % (pressure, temprature, result))
    
    #Create a input box for pressure
    box_pressure = Entry(myWindow)
    box_pressure.pack()
    
    #Create a input box for temprature
    box_temprature = Entry(myWindow)
    box_temprature.pack()
    
    #Create a button
    button_calculate = Button(myWindow, text="Calcuate", command=MyCalculateFunction)
    button_calculate.pack()
    
    #Create a label
    label_result = Label(myWindow)
    label_result.pack()
    

    或从文本变量中获取

    #Bind it with variable
    variable_pressure = DoubleVar()
    box_pressure = Entry(myWindow, textvariable=variable_pressure)
    box_pressure.pack()
    
    #Get/Set value by .get() / .set()
    variable_pressure.set(42)
    
    # shows 42
    print(variable_pressure.get())
    

    【讨论】:

    • 我真的做到了!
    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多