Python Tkinter - Combobox

Pybeginner
By -
0



We will learn how to add a Combobox into a tkinter. To add a combo box widget, you can use the Combobox class from the ttk library like this:

 

from tkinter.ttk import *

combo = Combobox(window)

 

Then you can add your values the combo box. So the full code will be as below:

 

from tkinter import *
from tkinter.ttk import *

window = Tk ()
window.title ("First Combobox")
window.geometry ('250x250')

combo = Combobox (window)
combo ['values'] = (1, 2, 3, 4, 5, "Hello")
combo.current (1) # defines the selected item
combo.grid (column = 0, row = 0, padx=10,pady=10)

window.mainloop ()

 



 

As you can see, we've added the items in the box combination using the tuple.

To define the selected item, you can pass the index of the desired item to the current function.

 

Python tkinter – How to get items from Combo box

 

We can also get the items from Combobox widget. To get the selected item, you can use the get function as follows:

combo.get ()

 

Exemple:

 

from tkinter import *
from tkinter.ttk import *

window = Tk()
window.title("First Combobox")
window.geometry('250x250')

def hello():
result = combo.get()
print(result)
label.configure(text=result)

label = Label(window, text="text")
label.grid(row=0,column=0, padx=10, pady=10)

combo = Combobox (window)
combo ['values'] = (1, 2, 3, 4, 5, "Hello")
combo.current(1) # defines the selected item
combo.grid(column = 0, row = 1, padx=10,pady=10)

button = Button(window, text = "Click here", command = hello)
button.grid column = 0, row = 2, padx = 5, pady = 15)

window.mainloop()

 



Now if we run the code and select an item from the combobox, and click on the button, it will print this result into our terminal, and will also update the text that is the the label with this selected item from combobox.

Post a Comment

0Comments

Post a Comment (0)