Python tkinter:使用“文本变量"在组合框中似乎没用 [英] Python tkinter: Using a "textvariable" in a combobox seems useless

查看:25
本文介绍了Python tkinter:使用“文本变量"在组合框中似乎没用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 tkinter 中创建组合框时使用 textvariable 属性似乎完全没用.有人可以解释一下目的是什么吗?我查看了 Tcl 文档,它说 textvariable 用于设置默认值,但看起来在 tkinter 中您只需使用 .set 方法来做到这一点.

Using the textvariable attribute when creating a combobox in tkinter seems completely useless. Can someone please explain what the purpose is? I looked in the Tcl documentation and it says textvariable is used to set a default value, but it looks like in tkinter you would just use the .set method to do that.

示例说明我的意思:

这不起作用...

from Tkinter import *
import ttk

master = Tk()

test = StringVar()
country = ttk.Combobox(master, textvariable=test)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()

# This does not set a default value...
test="hello"

mainloop()

这确实有效.

from Tkinter import *
import ttk

master = Tk()

country = ttk.Combobox(master)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()

# This does set a default value.
country.set("hello")

mainloop()

如果你应该只使用 .set.get 方法,那么给 textvariable 赋值有什么意义?网上的每个例子似乎都使用 textvariable,但为什么呢?这似乎完全没有意义.

If you are supposed to just use the .set and .get methods, what is the point of assigning anything to textvariable? Every example online seems to use textvariable, but why? It seems completely pointless.

推荐答案

在正常情况下没有理由使用StringVar.我不知道为什么大多数教程都会显示它.它增加了开销,但没有提供额外的价值.如您所见,您可以通过组合框对象本身直接获取和设置组合框的值.

Under normal circumstances there is no reason to use a StringVar. I have no idea why most tutorials show it. It adds overhead but provides no extra value. As you observe, you can directly get and set the value of the combobox via the combobox object itself.

使用 StringVar 的优势在于:a) 让两个小部件共享相同的变量,以便在另一个小部件更改时更新一个,或者 b) 附加一个或多个跟踪到 StringVar.这两者都不常见,但有时非常有用.

The advantage to using a StringVar comes when you want to either a) have two widgets share the same variable so that one is updated when the other is changed, or b) attach one or more traces to the StringVar. Both of those are uncommon, but are sometimes quite useful.

这篇关于Python tkinter:使用“文本变量"在组合框中似乎没用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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