如何从entry(Tkinter)获取值,如何在公式中使用它并将结果打印在标签中 [英] How to get value from entry(Tkinter), use it in formula and print the result it in label

查看:963
本文介绍了如何从entry(Tkinter)获取值,如何在公式中使用它并将结果打印在标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from Tkinter import *

top=Tk()

用户将输入的第一个值A

First Value A that user will input

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

用户还输入的第二个值B

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

结果-当我输入前两个值时,我希望python计算结果并将其显示给用户

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

推荐答案

首先,欢迎您使用StackOverflow,一切顺利-您的代码(大部分)可以完成您想要的所有工作!时机不对,您可以创建对象并获取值,但用户尚未输入值.

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.

要解决此问题,您需要将.get()放入函数中,并且应该在每个变量之后使用一个实际的文本变量,您可以在set()之后使用(如果您仅使用C1 =(float),您最终将制作新的浮动广告,因此Label指向的对象不正确.)

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

此外,您需要设置此功能,以便它不仅仅在立即运行程序"时关闭.实现此目的的简单方法是使函数本身.after()调用一段时间(以毫秒为单位).

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.


更新方式稍微更先进,更有效,它涉及事件和绑定(每次更改A1或B1时都会绑定绑定setC()来触发),但是有关该内容的内容很长,因此我将向您提供提示并发送给您对此的一些文档. (无论如何,Effbot都是很好的tkinter文档)


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)

这篇关于如何从entry(Tkinter)获取值,如何在公式中使用它并将结果打印在标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆