为什么tkinter.ttk Combobox仅在初始选择时清除显示值?

时间:2015-05-14 05:11:55

标签: python python-3.x combobox tkinter ttk

我正在tkinter建立一个gui,我看到ttk.Combobox的好奇行为。一切都初始化很好,但是当我从下拉列表中选择一个项目时,组合框显示清除。这只在我第一次做出选择时才会发生。所以我启动应用程序>选择> 显示清除>做另一个选择> diplay正常。这是代码(为简洁起见,只是相关部分)。组合框类从数据库中获取列作为列表并将其分配给值。否则,这是非常直接的tkinter。

import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from tkinter import N, S, E, W
from tkinter import END, CENTER

import dbmanager


class MainGUI(tk.Tk):

    """Main GUI class for EngCalc."""

    def __init__(self, db_mngr):
        """See class docstring."""
        self.db = db_mngr
        tk.Tk.__init__(self)
        tk.Tk.wm_title(self, 'EngCalc')
        self.init_root_frame(master=self)

    def init_root_frame(self, master=None):
        """Create and initialize main GUI container."""
        self.root_frame = ttk.Frame(master)
        self.root_frame.grid()

        DBCombo(master=self.root_frame, controller=self,
                table='[Materials(SI)]', col='Material')


class DBCombo(ttk.Combobox):

    """A dropdown combobox for a given column in database table."""

    def __init__(self, master=None, controller=None,
                 table=None, col=None, row=0, column=0):
        """See class docstring."""
        self.values = controller.db.fetch_list(table, col)
        self.combovar = tk.StringVar()
        ttk.Combobox.__init__(self, master, values=self.values,
                              textvariable=self.combovar)
        self.current(0)
        self.bind("<<ComboboxSelected>>", self.newselection)
        self.grid(column=column, row=row)
        self.state(['!disabled', 'readonly'])

    def newselection(self, event):
        """Get value of combobox."""
        self.combovar = self.get()
        print(self.combovar)


if __name__ == '__main__':
    db = '../db/test1.sqlite'
    database = dbmanager.DatabaseManager(db)
    foo = MainGUI(database)
    foo.mainloop()

1 个答案:

答案 0 :(得分:3)

代码self.combovar中的某一点指向StringVar的实例,但稍后您将self.combovar重新定义为字符串。解决方案是重新定义self.combovar内的newselection