AttributeError: module 'tkinter' has no attribute 'Combobox'
import tkinter as tk # Importing the Tkinter library
from tkinter import ttk # Importing ttk for styled widgets
my_w = tk.Tk() # Creating the main Tkinter window
my_w.geometry("300x150") # Setting the window size to 300x150 pixels
my_w.title("www.plus2net.com") # Adding a title to the window
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # List of month options
cb1 = ttk.Combobox(my_w, values=months, width=7) # Creating a combobox widget with the list of months
cb1.grid(row=1, column=1, padx=10, pady=20) # Adding the combobox to the grid layout
cb1.set('Apr') # Setting 'Apr' as the default selected option
my_w.mainloop() # Running the Tkinter event loop to display the window
By using cb1.set('Apr')
we are setting a default selected option for the Combobox. cb1.current(2)
to set it as default selection.
cb1.get()
cb1.current()
cb1.current()
is an integer so we used str() to convert the same to string before adding.
import tkinter as tk # Importing the Tkinter library
from tkinter import ttk # Importing ttk for styled widgets
my_w = tk.Tk() # Creating the main Tkinter window
my_w.geometry("300x150") # Setting the window size to 300x150 pixels
my_w.title("www.plus2net.com") # Adding a title to the window
def my_upd1(): # Function to update combobox selection
cb1.set('Apr') # Update selection to 'Apr'
l1.config(text=cb1.get() + ':' + str(cb1.current())) # Display selected value and its index
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # List of month options
cb1 = ttk.Combobox(my_w, values=months, width=7) # Creating a combobox with the list of months
cb1.grid(row=1, column=1, padx=10, pady=20) # Adding the combobox to the grid layout
b1 = tk.Button(my_w, text="set('Apr')", command=lambda: my_upd1()
) # Button to update combobox selectionb1.grid(row=1, column=2) # Adding button to the grid
l1 = tk.Label(my_w, text='Month') # Label to display selected month and index
l1.grid(row=1, column=3) # Adding label to the grid
print(cb1.get()) # Print the current value of the combobox
my_w.mainloop() # Running the Tkinter event loop to display the window
The code generates a window with a Combobox containing several colors. When the user selects a color, the label next to it will display the color name, and the background of the label will also change to match the selected color. This makes it a simple yet effective demonstration of the interaction between Tkinter widgets.
import tkinter as tk
from tkinter import ttk # import ttk
my_w = tk.Tk() # parent window
my_w.geometry("400x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
font1 = ['Arial', 22, 'normal'] # font style
def my_upd(*args):
l1.config(text=sel.get(), bg=sel.get()) # item name as text and background color
colors = ['red', 'green', 'blue', 'yellow', 'lightgreen']
sel = tk.StringVar() # string variable for the Combobox
cb1 = ttk.Combobox(my_w, values=colors, width=10,
textvariable=sel, font=font1)
cb1.grid(row=1, column=1, padx=10, pady=20)
l1 = tk.Label(my_w, text='Select colors', font=font1, width=10, anchor='center')
l1.grid(row=1, column=2, padx=5)
sel.trace_add('write', my_upd) # trigger the change in selection
my_w.mainloop() # Keep the window open
Passing Data from Child window to Combobox in Parent
cb1.set('Apr')
, same way we can reset the selection to blank by using cb1.set('')
or cb1.delete(0,'end')
def my_upd1(): # Function to update or clear combobox selection
# cb1.set('') # Clear the selection (commented out)
cb1.delete(0, 'end') # Clear the current selection in the combobox
l1.config(
text=cb1.get() + ':' + str(cb1.current())
) # Update label with the current value and index
cb1['values']
so we can't add or remove items from this. We will create a new list and then associate the cb1['values']
to this new list after removing the selected item.
def my_delete(): # Removing option from Combobox
my_new = [] # Blank list to hold new values
for opt in cb1['values']: # Loop through all options of the combobox (tuple)
if (opt != cb1.get()): # Check if the option is not the currently selected one
# print(opt) # Debugging line to print each option (commented out)
my_new.append(opt) # Add the option to the new list
cb1['values'] = my_new # Assign the updated list back to the combobox
cb1.delete(0, 'end') # Remove the current selection text
In our script below the above code is integrated.
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_upd(*args):
l1.config(text=sel.get()+ " : " + str(cb1.current()))
sel=tk.StringVar() # string variable
months=['Jan','Feb','Mar','Apr','May','Jun']
cb1 = ttk.Combobox(my_w, values=months,width=7, textvariable=sel)
cb1.grid(row=1,column=1,padx=10,pady=20)
l1=tk.Label(my_w,text='Month')
l1.grid(row=1,column=2)
sel.trace_add('write',my_upd)
my_w.mainloop() # Keep the window open
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_upd(*args):
l1.config(text=sel.get() + ' : '+ str(cb1.current()))
def my_insert(): # adding data to Combobox
#if e1.get() not in cb1['values']:
cb1['values'] +=(e1.get(),) # add option
sel=tk.StringVar() # string variable
months=['Jan','Feb','Mar','Apr','May','Jun']
cb1 = ttk.Combobox(my_w, values=months,width=7,textvariable=sel)
cb1.grid(row=1,column=1,padx=10,pady=20)
l1=tk.Label(my_w,text='Month')
l1.grid(row=1,column=2)
e1=tk.Entry(my_w,bg='Yellow',width=10)
e1.grid(row=1,column=3)
b1=tk.Button(my_w,text='Add',command=lambda: my_insert())
b1.grid(row=1,column=4)
sel.trace_add('write',my_upd)
my_w.mainloop() # Keep the window open
def my_insert(): # adding data to Combobox
if e1.get() not in cb1['values']: # check duplicate
cb1['values'] +=(e1.get(),) # add option
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("450x350") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_insert(): # adding data to Combobox
#if e1.get() not in cb1['values']: # prevent duplicates
cb1['values'] +=(e1.get(),) # add option
e1.delete(0,'end') # remove the current selection
def my_delete(): # removing option from the Combobox
my_new=[] # Blank list to hold new values
for opt in cb1['values']: # Loop through all options
if(opt != cb1.get()):
#print(opt)
my_new.append(opt) # Add to new list
cb1['values']=my_new # assign to new list
cb1.delete(0,'end') # remove from current selection text
sel=tk.StringVar() # string variable
months=['Jan','Feb','Mar']
cb1 = ttk.Combobox(my_w, values=months,width=7,textvariable=sel,font=22)
cb1.grid(row=1,column=1,padx=20,pady=30)
l1=tk.Label(my_w,text='Month')
l1.grid(row=1,column=2)
e1=tk.Entry(my_w,bg='Yellow',width=10,font=22)
e1.grid(row=1,column=3,padx=3)
b1=tk.Button(my_w,text='Add',command=lambda: my_insert(),font=18)
b1.grid(row=1,column=4)
b2=tk.Button(my_w,text='Delete',command=lambda: my_delete(),font=18)
b2.grid(row=1,column=5,padx=5)
#sel.trace_add('write',my_upd)
my_w.mainloop() # Keep the window open
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_upd1():
l1.config(text=str(cb1.current()) + ' : ' + cb1.get())
months=['Jan','Feb','Mar','Apr','May','Jun']
cb1 = ttk.Combobox(my_w, values=months,width=7)
cb1.grid(row=1,column=1,padx=10,pady=20)
b1=tk.Button(my_w,text="Read",command=lambda: my_upd1())
b1.grid(row=1,column=2)
l1=tk.Label(my_w,text='Month')
l1.grid(row=1,column=3)
my_w.mainloop() # Keep the window open
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
my_dict = {
1: 'Jan',
2: 'Feb',
3: 'March',
4: 'April',
5: 'May'
}
months = list(my_dict.values()) # Extract list of month names
font1 = ('Times', 18, 'normal')
def my_upd(*args):
l1.config(text=sel.get()) # Month name as string
for i, j in my_dict.items():
if j == sel.get():
l2.config(text=i) # Month number
sel = tk.StringVar() # String variable for the Combobox
cb1 = ttk.Combobox(my_w, values=months, width=7,
textvariable=sel, font=font1)
cb1.grid(row=1, column=1, padx=10, pady=20)
l1 = tk.Label(my_w, text='Month-Name', font=font1)
l1.grid(row=1, column=2, padx=5)
l2 = tk.Label(my_w, text='Month-No', font=font1)
l2.grid(row=1, column=3, padx=5)
sel.trace_add('write', my_upd)
my_w.mainloop() # Keep the window open
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
my_dict = {'A':5, 'B':4, 'C':3,
'D':3, 'E':1, 'F':0}
months = list(my_dict.keys()) # All keys are taken as options
font1 = ('Times', 18, 'normal')
def my_upd(*args):
str1.set(sel.get()) # Key name A B C D is displayed
str2.set(my_dict[sel.get()]) # Value of the key is displayed
sel = tk.StringVar() # String variable for the Combobox
cb1 = ttk.Combobox(my_w, values=months, width=7,
textvariable=sel, font=font1)
cb1.grid(row=1, column=1, padx=10, pady=20)
str1 = tk.StringVar() # String variable for entry1
str2 = tk.StringVar() # String variable for entry2
l1 = tk.Entry(my_w, font=font1, width=5, textvariable=str1)
l1.grid(row=1, column=2, padx=5)
l2 = tk.Entry(my_w, font=font1, width=5, textvariable=str2)
l2.grid(row=1, column=3, padx=5)
sel.trace_add('write', my_upd)
my_w.mainloop() # Keep the window open
The code generates a window with a Combobox containing product names. When the user selects a product, the label next to it will display the product name, and the adjacent label will display the product details. This is a simple example demonstrating the interaction between Tkinter widgets and how to use a dictionary to provide additional details based on user selection.
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x150") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
# Item list where options of combobox are the keys of the dictionary
my_dict = {
'item 1': ['I -1', 'Medium', 40],
'item 2': ['I -2', 'High', 60],
'item 3': ['I -3', 'Low', 20],
'item 4': ['I -4', 'Best', 70]
}
products = list(my_dict.keys()) # List of keys as options of combobox
font1 = ('Times', 18, 'normal')
def my_upd(*args):
l1.config(text=sel.get()) # Item name as text
my_str = ",".join(map(str, my_dict[sel.get()])) # Combine list values into a string
l2.config(text=my_str) # Set details as text
sel = tk.StringVar() # String variable for the Combobox
cb1 = ttk.Combobox(my_w, values=products, width=7,
textvariable=sel, font=font1)
cb1.grid(row=1, column=1, padx=10, pady=20)
l1 = tk.Label(my_w, text='Product', font=font1)
l1.grid(row=1, column=2, padx=5)
l2 = tk.Label(my_w, text='Details', font=font1)
l2.grid(row=1, column=3, padx=5)
sel.trace_add('write', my_upd) # Triggers on change of StringVar (Combobox)
my_w.mainloop() # Keep the window open
import tkinter as tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150+400+50") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_upd():
print(r_v.get())
if r_v.get():
cb1.config(state='active') #normal
else:
cb1.config(state='disabled')
r_v=tk.BooleanVar()
months=['Jan','Feb','Mar','Apr','May']
cb1=ttk.Combobox(my_w,values=months,width=10)
cb1.grid(row=1,column=1,padx=10,pady=10)
r_v.set(True)
r1 = tk.Radiobutton(my_w, text='Enable', variable=r_v,
value=True,command=my_upd)
r1.grid(row=1,column=2)
r2 = tk.Radiobutton(my_w, text='Disable', variable=r_v,
value=False,command=my_upd)
r2.grid(row=1,column=3)
my_w.mainloop() # Keep the window open
'readonly'
: In this state, the user cannot type or edit the text field directly but can still select an option from the dropdown list. This is useful when we want to restrict the input to the predefined set of options only.
height | Height of the drop-down list box. |
postcommand | Function or script is called before displaying the values |
values | The list of values to be included as options. ( See the examples above ) |
exportselection | True / False, Managing export of selection to Clipboard |
font | Assign font style , size to user entry data ( not the list ). To change the font style of list box use this. |
invalidcommand | specifies a callback function that is called whenever the validatecommand returns False |
justify | Alignment of data, takes value 'left' (default ),'center', 'right' |
show | Char to be used for masking the user entry and selected option |
state | normal | active | disabled | readonly, |
textvariable | Connected variable to be used . (See the examples above) |
validate | dynamic validation of the widget's text content. |
validatecommand | callback function that dynamically validates the widget's text content |
values | Options that will appear as choice. |
width | Width of the combobox |
xscrollcommand | connect to one Scorollbar |
foreground | Font colour |
background | Background colour |
takefocus | True | False Widget will be included in focus traversal or not. |
cursor | Shape of the cursor while moving over the panes. ( List of cursor shapes ) |
style | The style to be used in rendering |
class | The widget class name |
for options in cb1.config():
print(options + ": " + str(cb1[options]))
29-07-2022 | |
Dear Sir, Thank you for your good instructions. I learn a lot from your videos. One question: how to delete the combobox option dynamicly? i was unable to use cb1['values'] -=(e1.get(),) to delete the option. please kindly teach me how to do it. Thank you very much. I subcribed your yourtube already. ST |
05-08-2022 | |
You can't delete by using cb1['values'] -=(e1.get(),) as it is a tuple. Create a new tuple with all the options except the one you want to delete. Then assign the new tuple to cb1. This part is added to this page. Here is the video again. https://youtu.be/PICzrYI6O9A |
22-11-2022 | |
In one of the programs which i am working , the combo box freezes when i click on dropdown and then the application stops and crashes. Please advise |
08-01-2023 | |
Are you using any onclick event and triggering any function? Just remove the function and see how it is working. Then check the code inside the function. |