Christopher Pearson
Christopher Pearson

Reputation: 1193

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. 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. 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()

Upvotes: 2

Views: 1879

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

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. The solution is to not redefine self.combovar inside newselection

Upvotes: 3

Related Questions