简体   繁体   English

为什么tkinter.ttk组合框仅在初始选择时清除显示的值?

[英]Why does tkinter.ttk Combobox clear displayed value on initial selection only?

I am building a gui in tkinter and I am seeing a curious behaviour for a ttk.Combobox . 我正在ttk.Combobox构建gui,并且看到了ttk.Combobox的奇怪行为。 Everything initializes fine, but when I select an item from the dropdown, the combobox display clears. 一切初始化都很好,但是当我从下拉列表中选择一个项目时,组合框显示将清除。 This only happens the first time I make a selection. 这仅在我第一次选择时发生。 So I start the app > make a selection > display clears > make another selection > diplays normal. 因此,我启动了应用程序>进行选择> 显示清除 >进行其他选择>正常播放。 Here's the code (only pertinent parts for brevity). 这是代码(为简洁起见,仅是相关部分)。 The combobox class fetches a column from a database as a list and assigns that to the values. combobox类从数据库中获取一列作为列表,并将其分配给值。 Otherwise, it is pretty straighforward 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()

At one point in your code self.combovar points to an instance of a StringVar , but later you redefine self.combovar to be a string. 在代码中的一点上, self.combovar指向StringVar的实例,但是稍后您将self.combovar重新定义为字符串。 The solution is to not redefine self.combovar inside newselection 解决方案是不在 self.combovar内部重新定义newselection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM