Python tkinter combobox insert

Tkinter Combobox

Summary: in this tutorial, you’ll learn to create a Tkinter combobox widget that allows users to select one value from a set of values.

Introduction to the Tkinter Combobox widget

A combobox is a combination of an Entry widget and a Listbox widget. A combobox widget allows you to select one value in a set of values. In addition, it allows you to enter a custom value.

Create a combobox

To create a combobox widget, you’ll use the ttk.Combobox() constructor. The following example creates a combobox widget and links it to a string variable:

current_var = tk.StringVar() combobox = ttk.Combobox(container, textvariable=current_var)Code language: Python (python)

The container is the window or frame on which you want to place the combobox widget.

The textvariable argument links a variable current_var to the current value of the combobox.

To get the currently selected value, you can use the current_var variable:

current_value = current_var.get()Code language: Python (python)

Alternatively, you can use the get() method of the combobox object:

current_value = combobox.get()Code language: Python (python)

To set the current value, you use the current_var variable or the set() method of the combobox object:

current_value.set(new_value) combobox.set(new_value)Code language: Python (python)

Define value list

The combobox has the values property that you can assign a list of values to it like this:

combobox['values'] = ('value1', 'value2', 'value3')Code language: Python (python)

By default, you can enter a custom value in the combobox. If you don’t want this, you can set the state option to ‘readonly’ :

combobox['state'] = 'readonly'Code language: Python (python)

To re-enable editing the combobox, you use the ‘normal’ state like this:

combobox['state'] = 'normal'Code language: Python (python)

Bind events

When a select value changes, the combobox widget generates a ‘>’ virtual event. To handle the event, you can use the bind() method like this:

combobox.bind('>', callback)Code language: Python (python)

In this example, the callback function will execute when the selected value of the combobox changes.

Читайте также:  Get text document html

Set the current value

To set the current value, you use the set() method:

combobox.set(self, value)Code language: Python (python)

Also, you can use the current() method:

current(self, newindex=None)Code language: Python (python)

The newindex specifies the index of values from the list that you want to select as the current value.

If you don’t specify the newindex , the current() method will return the index of the current value in the list of values or -1 if the current value doesn’t appear in the list.

Python Tkinter combobox example

The following program illustrates how to create a combobox widget:

import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo from calendar import month_name root = tk.Tk() # config the root window root.geometry('300x200') root.resizable(False, False) root.title('Combobox Widget') # label label = ttk.Label(text="Please select a month:") label.pack(fill=tk.X, padx=5, pady=5) # create a combobox selected_month = tk.StringVar() month_cb = ttk.Combobox(root, textvariable=selected_month) # get first 3 letters of every month name month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)] # prevent typing a value month_cb['state'] = 'readonly' # place the widget month_cb.pack(fill=tk.X, padx=5, pady=5) # bind the selected value changes def month_changed(event): """ handle the month changed event """ showinfo( title='Result', message=f'You selected !' ) month_cb.bind('>', month_changed) root.mainloop()Code language: Python (python)

The following program shows the same month combobox widget and uses the set() method to set the current value to the current month:

import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo from calendar import month_name from datetime import datetime root = tk.Tk() # config the root window root.geometry('300x200') root.resizable(False, False) root.title('Combobox Widget') # label label = ttk.Label(text="Please select a month:") label.pack(fill=tk.X, padx=5, pady=5) # create a combobox selected_month = tk.StringVar() month_cb = ttk.Combobox(root, textvariable=selected_month) # get first 3 letters of every month name month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)] # prevent typing a value month_cb['state'] = 'readonly' # place the widget month_cb.pack(fill=tk.X, padx=5, pady=5) # bind the selected value changes def month_changed(event): """ handle the month changed event """ showinfo( title='Result', message=f'You selected !' ) month_cb.bind('>', month_changed) # set the current month current_month = datetime.now().strftime('%b') month_cb.set(current_month) root.mainloop()Code language: Python (python)

Summary

  • Use ttk.Combobox(root, textvariable) to create a combobox.
  • Set the state property to readonly to prevent users from entering custom values.
  • A combobox widget emits the ‘>’ event when the selected value changes.

Источник

Python tkinter combobox insert

Виджет Combobox представляет выпадающий список, из которого пользователь может выбрать один элемент. Фактически он представляет комбинацию виджетов Entry и Listbox.

Основные параметры конструктора Combobox:

  • values : список строк для отображения в Combobox
  • background : фоновый цвет
  • cursor : курсор указателя мыши при наведении на текстовое поле
  • foreground : цвет текста
  • font : шрифт текста
  • justify : устанавливает выравнивание текста. Значение LEFT выравнивает текст по левому краю, CENTER — по центру, RIGHT — по правому краю
  • show : задает маску для вводимых символов
  • state : состояние элемента, может принимать значения NORMAL (по умолчанию) и DISABLED
  • textvariable : устанавливает привязку к элементу StringVar
  • height : высота элемента
  • width : ширина элемента

Определим простейший выпадающий список:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") languages = ["Python", "C#", "Java", "JavaScript"] combobox = ttk.Combobox(values=languages) combobox.pack(anchor=NW, padx=6, pady=6) root.mainloop()

Здесь для элемента combobox в качестве источника значений устанавливается список languages:

Combobox в Tkinter и Python

С помощью параметра textvariable мы можем установить привязку к выбранному в Combobox значению:

from cProfile import label from cgitb import text from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") languages = ["Python", "C#", "Java", "JavaScript"] # по умолчанию будет выбран первый элемент из languages languages_var = StringVar(value=languages[0]) label = ttk.Label(textvariable=languages_var) label.pack(anchor=NW, padx=6, pady=6) combobox = ttk.Combobox(textvariable=languages_var, values=languages) combobox.pack(anchor=NW, padx=6, pady=6) print(combobox.get()) root.mainloop()

Здесь выбранный в Combobox элемент привязан к переменной languages_var. По умолчанию выбран первый элемент списка languages. Для отслеживания изменения выбора определена метка Label, которая отображает выбранный элемент:

Получение выбранного элемента в Combobox в Tkinter и Python

По умолчанию мы можем ввести в текстовое поле в Combobox любое значение, даже то, которого нет в списке. Такое поведение не всегда может быть удобно. В этом случае мы можем установить для виджета состояние только для чтения, передав параметру «state» значение «readonly»:

combobox = ttk.Combobox(textvariable=languages_var, values=languages, state="readonly")

Выбранный элемент можно получить с помощью метода get() класса Combobox

либо с помощью метода get() привязанной переменной

selection = languages_var.get()

Для установки нового значения можно использовать метод set() :

languages_var.set(new_value) combobox.set(new_value)

Для установки по индексу из привязанного набора значений также можно использовать метод current(newindex) , где с помощью параметра newindex задается индекс выбранного значения. Например, выберем второй элемент:

Отслеживание выбора значения

Для обработки выбора элементов в Combobox необходимо прикрепить функцию обработки к событию > с помощью метода bind :

combobox.bind(">", функция_обработки)

Например, динамически обработаем выбор в Combobox:

from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") def selected(event): # получаем выделенный элемент selection = combobox.get() print(selection) label["text"] = f"вы выбрали: " languages = ["Python", "C#", "Java", "JavaScript"] label = ttk.Label() label.pack(anchor=NW, fill=X, padx=5, pady=5) combobox = ttk.Combobox(values=languages, state="readonly") combobox.pack(anchor=NW, fill=X, padx=5, pady=5) combobox.bind(">", selected) root.mainloop()

В данном случае при изменении выбора в списке срабатывает функция selected . Функция должна принимать один параметр, который несет информацию о событии — здесь это параметр event. Хотя в данном случае он никак не используется.

В самой функции получаем выбранный элемент и выводит соответствующую информацию на метку Label.

Источник

Оцените статью