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

不打扰是莪最后的温柔 提交于 2020-01-07 15:20:21

问题


from Tkinter import *

top=Tk()

First Value A that user will input

A = Entry(top)
A.grid(row=1, column=1)

Second value B that user also inputs

B = Entry(top)
B.grid(row=1, column=2)

Calculation - Now I want to add those values (Preferably values with decimal points)

A1=float(A.get())
B1=float(B.get())
C1=A1+B1

Result - I want python to calculate result and show it to user when I input the first two values

C = Label(textvariable=C1)
C.grid(row=1, column=3)


top.mainloop()

回答1:


First off, welcome to StackOverflow and nice job- your code does (mostly) everything you want it to do! The timing is just off- you create your objects and get the value, but the value hasn't been input by the user yet.

To solve that, you need to put your .get()'s in a function, and you should be using an actual text-variable that you set() after each one (if you just use C1=(float), you'll end up making new floats so the Label isn't pointing to the right one).

(setup... )
B.grid(...)
C1 = Tkinter.StringVar()
C = Label(textvariable=C1) # Using a StringVar will allow this to automagically update

def setC():
    A1=float(A.get())
    B1=float(B.get())
    C1.set(str(A1+B1))

Additionally, you need to set this function so it goes off more than just "immediately on running the program". The simple way to do this is to just have the function call itself .after() some time (in milliseconds).

def setC():
    # Body above
    top.after(1000, setC) # Call setC after 1 second, so it keeps getting called.

setC() # You have to call it manually once, and then it repeats.

The slightly more advanced and efficient way to update involves events and bindings (binding setC() to fire every time A1 or B1 is changed), but the writeup on that is long so I'll give you that tip and send you to some documentation on that. (Effbot is good tkinter documentation regardless)



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

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