How to get value from entry (Tkinter), use it in formula and print the result it in label

让人想犯罪 __ 提交于 2019-12-13 09:48:20

问题


When using the function entry of Tkinter, you can write a string value and do things with it; but I'm actually working with formulas. The idea is fairly simple: to put a bunch of boxes to fill with numbers (pressure, thrust, stress, temperature and so on) and then take that numbers, apply the formulas and show the results in the same window.

How can I do that?

I've been searching for hours and hours without getting a non confusing solution.

Seems like the guy in this page had the same trouble, but I did not understand a nut of the solution: How to get value from entry(Tkinter), use it in formula and print the result it in label

Here as well is another example of the few (just 2) I could get, but for me, is way complicated than the previous above:

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

If someone could share a full program which explains me how can I apply that concept of taking numerical values from string entries in my future projects, I will be so so so glad.


回答1:


You can either get values by .get() from widgets

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()

or get it from textvariable

#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())


来源:https://stackoverflow.com/questions/53313470/how-to-get-value-from-entry-tkinter-use-it-in-formula-and-print-the-result-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!