为 ttk Combobox 设置默认值 [英] Set a default value for a ttk Combobox

查看:143
本文介绍了为 ttk Combobox 设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Arch Linux x86_64 中使用 Python 3.2.1.这个真的让我发疯:我只想在我网格后立即为 ttk.Combobox 设置一个默认的预选值.这是我的代码:

I'm using Python 3.2.1 in Arch Linux x86_64. This one is really driving me crazy: I just want to have a default, preselected value for a ttk.Combobox as soon as I grid it. This is my code:

from tkinter import Tk, StringVar, ttk

root = Tk()

def combo(parent):
    value = StringVar()
    box = ttk.Combobox(parent, textvariable=value, state='readonly')
    box['values'] = ('A', 'B', 'C')
    box.current(0)
    box.grid(column=0, row=0)

combo(root)

root.mainloop()

绘制一个空的Combobox.有趣的是,如果我不使用函数,它就可以完美运行:

Which draws an empty Combobox. What's funny is that if I don't use a function it works perfectly:

from tkinter import Tk, StringVar, ttk

root = Tk()

value = StringVar()
box = ttk.Combobox(root, textvariable=value, state='readonly')
box['values'] = ('A', 'B', 'C')
box.current(0)
box.grid(column=0, row=0)

root.mainloop()

当然,在实际程序中我必须使用函数,所以我需要另一种解决方案.

Of course, in the real program I have to use a function, so I need another solution.

推荐答案

问题是 StringVar 的实例正在被垃圾收集.这是因为由于您编写代码的方式,它是一个局部变量.

The problem is that the instance of StringVar is getting garbage-collected. This is because it's a local variable due to how you wrote your code.

一种解决方案是使用一个类,以便您的 StringVar 保持不变:

One solution is to use a class so that your StringVar persists:

from tkinter import Tk, StringVar, ttk

class Application:

    def __init__(self, parent):
        self.parent = parent
        self.combo()

    def combo(self):
        self.box_value = StringVar()
        self.box = ttk.Combobox(self.parent, textvariable=self.box_value, 
                                state='readonly')
        self.box['values'] = ('A', 'B', 'C')
        self.box.current(0)
        self.box.grid(column=0, row=0)

if __name__ == '__main__':
    root = Tk()
    app = Application(root)
    root.mainloop()

这篇关于为 ttk Combobox 设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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