In this TKinter Tutorial we are going to learn creating TKinter ComboBox, so a combo box is a commonly used graphical user interface widget. Traditionally, it is a combination of a drop-down list or list box.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
from tkinter import * from tkinter import ttk class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("ComboBox In TKinter ") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_combo() def click_me(self): self.label.configure(text = "Selected :" + self.languages.get()) def create_combo(self): self.languages = StringVar() self.combobox = ttk.Combobox(self, width = 20, textvariable = self.languages) self.combobox['values'] = ("Python", "Java", "C++", "C#", "Ruby", "PHP", "CSS") self.combobox.grid(column = 1, row = 0) self.label = ttk.Label(self, text = "Select Your Language") self.label.grid(column=0, row=0) self.button = ttk.Button(self, text = "Click ME", command = self.click_me) self.button.grid(column=2, row=0) window = Window() window.mainloop() |
We are going to use combobox from ttk, you can give the width for the combobox.
1 |
self.combobox = ttk.Combobox(self, width = 20, textvariable = self.languages) |
These are the items that we want to add in our combobox.
1 |
self.combobox['values'] = ("Python", "Java", "C++", "C#", "Ruby", "PHP", "CSS") |
In here we have added our tkinter combobox in grid layout.
1 |
self.combobox.grid(column = 1, row = 0) |
This is the label that we have created, also we have added the label in the grid layout.
1 2 |
self.label = ttk.Label(self, text = "Select Your Language") self.label.grid(column=0, row=0) |
Also we have created a button in here, we have added a command to our button, when we click on the button we want to print the combobox item in the label.
1 2 |
self.button = ttk.Button(self, text = "Click ME", command = self.click_me) self.button.grid(column=2, row=0) |
This is the method that we have already connected with our button, and basically we are going to change the text of the label with value of combobox.
1 2 |
def click_me(self): self.label.configure(text = "Selected :" + self.languages.get()) |
Run the complete code and this is the result.