如何将变量连接到 Entry 小部件? [英] How to connect a variable to Entry widget?

查看:22
本文介绍了如何将变量连接到 Entry 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量与 Tkinter 条目小部件相关联,方式如下:

I'm trying to associate a variable with a Tkinter entry widget, in a way that:

  1. 每当我更改条目的值(内容")时,主要是通过在其中输入内容,变量会自动获得我所输入内容的值.无需我先按下更新值"或类似按钮.

  1. Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like that first.

每当变量改变时(由程序的其他部分),我希望显示的条目值自动调整.我相信这可以通过 textvariable 起作用.

Whenever the variable gets changed (by some other part of the programm), I want the entry value displayed to be adjusted automatically. I believe that this could work via the textvariable.

我阅读了 http://effbot.org/tkinterbook/entry.htm,但它并不能完全帮助我实现我的想法.我觉得有一种方法可以通过使用条目的验证"来确保第一个条件.有什么想法吗?

I read the example on http://effbot.org/tkinterbook/entry.htm, but it is not exactly helping me for what I have in mind. I have a feeling that there is a way of ensuring the first condition with using entry's "validate". Any ideas?

推荐答案

我想你想要这样的东西.在下面的示例中,我创建了一个变量 myvar 并将其分配为 LabelEntrytextvariable小部件.这样两者是耦合的,并且 Entry 小部件中的更改将自动反映在 Label 中.

I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.

您还可以设置跟踪变量,例如写入标准输出.

You can also set trace on variables, e.g. to write to stdout.

from tkinter import *


root = Tk()
root.title("MyApp")

myvar = StringVar()

def mywarWritten(*args):
    print "mywarWritten",myvar.get()

myvar.trace("w", mywarWritten)

label = Label(root, textvariable=myvar)
label.pack()

text_entry = Entry(root, textvariable=myvar)
text_entry.pack()

root.mainloop()

这篇关于如何将变量连接到 Entry 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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