Combobox not displaying (Tkinter)

Question:

Im trying to use a combobox in my program.

To simplify my program, my main window uses an image as a background, and my buttons and entry boxes I wont include since they arent relavent. The code for my main window is:

from tkinter.ttk import Combobox
from tkinter.ttk import *
import tkinter as tk #importing tkinter library
from tkinter import * #importing everything from tkinter library

def main_window():
        # create a new window
    invoice = Toplevel()
    # load the image file
    billimage1 = PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/billimage.PNG")
    # create a label widget and set it as the background of the window
    label2 = Label(invoice, image = billimage1)
    label2.pack()

Im creating a function to include the combobox and calling it under the main_window function so it can be displayed over my image background. The code for it:

def dropdown():
 # create the Combobox widget
 options = ["option1", "option2", "option3"]
 combobox = ttk.Combobox(invoice, values=options)

 # create a frame to hold the Combobox
 frame = tk.Frame(invoice, width=200, height=50)
 frame.pack()

 # add the Combobox to the frame
 combobox.place(x=50, y=50)
dropdown()

If I dont call it, the program is runnable but is not displayed but when I do call it, it gives me an error saying: AttributeError: module ‘tkinter’ has no attribute ‘Combobox’.

I have the latest version of Python installed so that cant be the problem.

I tried packing it, then using place() but none of it worked. I kept on getting the error and so I uninstalled and then installed Python again yet im still receiving the error. Please Help!

Asked By: afggg

||

Answers:

The error message you received is due to a typo in your code. You imported the Combobox class from the tkinter.ttk module, but you are trying to create an instance of it using ttk.Combobox, which should be Combobox instead.

To fix the issue, you need to change ttk.Combobox to Combobox:

def dropdown():
    # create the Combobox widget
    options = ["option1", "option2", "option3"]
    combobox = Combobox(invoice, values=options)

    # create a frame to hold the Combobox  
    frame = tk.Frame(invoice, width=200, height=50)
    frame.pack()

    # add the Combobox to the frame
    combobox.place(x=50, y=50)

dropdown()

Additionally, you need to make sure that you have imported both the Combobox class and the ttk module. You can do this by adding the following imports to the top of your script:

from tkinter.ttk import Combobox
import tkinter as tk

With these changes, your code should work as expected.