scan
scan

Reputation: 107

default value for ttk.Combobox with dic

I know the subject is not new but I could not find a way to use it with the dictionary!

The problem is, if I make a call without making a selection in the ComboBox, it gives a NameError. I guess I can not do "try, except" because it is in the function "cbx_fatura_arama".

here is my code:

from tkinter import *
from tkinter import ttk

LframeAra = Tk()

class NewCBox(ttk.Combobox):
    def __init__(self, master, dictionary, *args, **kw):
        ttk.Combobox.__init__(self, master, values = sorted(list(dictionary.keys())), state = 'readonly', *args, **kw)

        self.dictionary = dictionary
        self.bind('<<ComboboxSelected>>', self.selected) #purely for testing purposes

    def value(self):
        return self.dictionary[self.get()]

    def selected(self, event): #Just to test
        global cbx_fatura_arama
        cbx_fatura_arama = self.value()


lookup = {'Firma' : 'firma', 'Fatura No' : 'fatura_no', 'Ürün Türü' : 'urun_turu', 'Model No' : 'model_no'}
newcb = NewCBox(LframeAra, lookup)
newcb.grid(row=1, column=7, padx=4, pady=4, sticky='we')

ara_ft = ttk.Entry(LframeAra)
ara_ft.grid(row=1, column=8, padx=4, pady=4, sticky='we')

ara_ft_button = ttk.Button(LframeAra, text="Ara", command=lambda : fatura_ara(cbx_fatura_arama, ara_ft))
ara_ft_button.grid(row=1, column=9, padx=4, pady=4, sticky='we') 

def fatura_ara(search, find):
    print("Some codes.........", search, find.get() )
mainloop()

What I need is to prevent the ComboBox from making mistakes in making selections. Or can make a default choice.

Could you suggest a way to do this? Thanks in advance.

Upvotes: 0

Views: 288

Answers (1)

Novel
Novel

Reputation: 13729

This is because you don't initialize your global variable. Why are you using a global variable anyway? It would be much better to simply get the value as you need it, rather than updating a variable with every change. For instance:

from tkinter import *
from tkinter import ttk

LframeAra = Tk()

class NewCBox(ttk.Combobox):
    def __init__(self, master, dictionary, *args, **kw):
        ttk.Combobox.__init__(self, master, values = sorted(list(dictionary.keys())), state = 'readonly', *args, **kw)
        self.current(0) # select the first option
        self.dictionary = dictionary

    def get(self):
        return self.dictionary[super().get()]

def fatura_ara():
    print("Some codes.........", newcb.get(), ara_ft.get())

lookup = {'Firma' : 'firma', 'Fatura No' : 'fatura_no', 'Ürün Türü' : 'urun_turu', 'Model No' : 'model_no'}
newcb = NewCBox(LframeAra, lookup)
newcb.grid(row=1, column=7, padx=4, pady=4, sticky='we')

ara_ft = ttk.Entry(LframeAra)
ara_ft.grid(row=1, column=8, padx=4, pady=4, sticky='we')

ara_ft_button = ttk.Button(LframeAra, text="Ara", command=fatura_ara)
ara_ft_button.grid(row=1, column=9, padx=4, pady=4, sticky='we')

mainloop()

Upvotes: 2

Related Questions