Python tkinter:在组合框中使用“文本变量”似乎没用

tjw*_*992 2 python combobox tkinter

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

示例显示我的意思:

这不起作用...

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()
Run Code Online (Sandbox Code Playgroud)

这确实有效。

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()
Run Code Online (Sandbox Code Playgroud)

如果您应该只使用.set.get方法,那么将任何内容分配给 有什么意义textvariable?网上的每个例子似乎都使用textvariable,但为什么呢?这似乎完全没有意义。

Squ*_*all 5

由于 Python 没有类型安全性,因此您将StringVar使用字符串覆盖对对象的引用。要设置该值,请调用该set方法:

test = StringVar()
country = ttk.Combobox(master, textvariable=test)
#...
test.set("hello")
Run Code Online (Sandbox Code Playgroud)


Bry*_*ley 5

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

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