Search code examples
pythonpython-3.xtkintercombobox

Show label if combobox value is selectek Tkinter Python3


I need to show/add a label and a textbox when I select a certain value in the combobox. I found this question and it helped but I still didn't get the desired output.

the purpose is the show the label vlan and the textbox when I select the value Single tagged in the combobox. This is my code :

from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk
from tkinter import Label, Entry, StringVar

root = Tk()
 
root.title('Traffic generation') 
root.geometry('250x250') 
ttk.Label(root, text = "Traffic generation",  
          background = 'light blue', foreground ="white",  
          font = ("Times New Roman", 15)).grid(row = 0, column = 1, sticky='NESW') 
          
cmb = ttk.Combobox(root, width="10", values=(' Untagged',' Single tagged',' Double tagged'))
               
def handler(event):
    current = cmb.current()
    if current == ' Single tagged':

        labelText=StringVar()
        labelText.set("VLAN")
        labelDir=Label(root, textvariable=labelText, height=4)
        labelDir.grid(row=2,column=0,sticky='s')        
        
        directory=StringVar(None)
        dirname=Entry(root,textvariable=directory,width=50)
        dirname.grid(row=2,column=1,sticky='e')
#cmb = Combobox
cmb.bind('<<ComboboxSelected>>', handler)
cmb.grid(row=1,column=0,sticky='s')

class TableDropDown(ttk.Combobox):
    def __init__(self, parent):
        self.current_table = tk.StringVar() # create variable for table
        ttk.Combobox.__init__(self, parent)#  init widget
        self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices"])
        self.current(0) # index of values for current table
        self.place(x = 50, y = 50, anchor = "w") # place drop down box 

def checkcmbo():

    if cmb.get() == " Untagged":
        messagebox.showinfo("What user choose", "you chose Untagged")

    elif cmb.get() == " Single tagged":
        messagebox.showinfo("What user choose", "you choose Single tagged")

    elif cmb.get() == " Double tagged":              
        messagebox.showinfo("What user choose", "you choose Double tagged")
        
    elif cmb.get() == "":
        messagebox.showinfo("nothing to show!", "you have to be choose something")

cmb.place(relx="0.1",rely="0.1")
btn = ttk.Button(root, text="Select mode",command=checkcmbo)
btn.place(relx="0.5",rely="0.1")
root.mainloop()

Solution

  • The problem is that Combobox.current() will return the index not the value.

    There are two solutions:

    1. change if current == ' Single tagged': to if current == 1.
    2. change if current == ' Single tagged': to if cmb.get() == ' Single tagged':.