Combobox tkinter python get

Getting the selected value from combobox in Tkinter

I’ve made a simple combobox in python using Tkinter, I want to retrieve the value selected by the user. After searching, I think I can do this by binding an event of selection and call a function that will use something like box.get(), but this is not working. When the program starts the method is automatically called and it doesn’t print the current selection. When I select any item from the combobox no method gets called. Here is a snippet of my code:

 self.box_value = StringVar() self.locationBox = Combobox(self.master, textvariable=self.box_value) self.locationBox.bind(">", self.justamethod()) self.locationBox['values'] = ('one', 'two', 'three') self.locationBox.current(0) 
def justamethod (self): print("method is called") print (self.locationBox.get()) 

Can anyone please tell me how to get the selected value? EDIT: I’ve corrected the call to justamethod by removing the brackets when binding the box to a function as suggested by James Kent. But now I’m getting this error: TypeError: justamethod() takes exactly 1 argument (2 given) EDIT 2: I’ve posted the solution to this problem. Thank You.

in your self.locationBox.bind you are calling the function by adding the brackets after the function name, remove these and it should work. so change self.justamethod() to self.justamethod

@JamesKent Thanks a lot, I always keep forgetting to remove the brackets. I removed them, but I’m getting this error, TypeError: justamethod() takes exactly 1 argument (2 given). Cany you please tell me how to solve it? Thanks.

the reason for the TypeError is because when the event is triggered, an event object is passed to the function you bound to as one of the arguments, if you want to see some of the attributes that can be got from this object, see this page: effbot.org/tkinterbook/tkinter-events-and-bindings.htm

2 Answers 2

I’ve figured out what’s wrong in the code.

First, as James said the brackets should be removed when binding justamethod to the combobox.

Second, regarding the type error, this is because justamethod is an event handler, so it should take two parameters, self and event, like this,

def justamethod (self, event): 

After making these changes the code is working well.

from tkinter import ttk from tkinter import messagebox from tkinter import Tk root = Tk() root.geometry("400x400") #^ width - heghit window :D cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai")) #cmb = Combobox class TableDropDown(ttk.Combobox): def __init__(self, parent): self.current_table = tk.StringVar() # create variable for table ttk.Combobox.__init__(self, parent)# init widget self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"]) self.current(0) # index of values for current table self.place(x = 50, y = 50, anchor = "w") # place drop down box def checkcmbo(): if cmb.get() == "prova": messagebox.showinfo("What user choose", "you choose prova") elif cmb.get() == "ciao": messagebox.showinfo("What user choose", "you choose ciao") elif cmb.get() == "come": messagebox.showinfo("What user choose", "you choose come") elif cmb.get() == "stai": messagebox.showinfo("What user choose", "you choose stai") elif cmb.get() == "": messagebox.showinfo("nothing to show!", "you have to be choose something") cmb.place(relx="0.1",rely="0.1") btn = ttk.Button(root, text="Get Value",command=checkcmbo) btn.place(relx="0.5",rely="0.1") root.mainloop() 

When answering, please provide an explanation of your code, and why it should solve the OP’s problem. Thank you

Читайте также:  Ubuntu nginx php fpm wordpress

Источник

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.

Читайте также:  Работа верстка html css

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.

Источник

Get combobox value in python

I’m developing an easy program and I need to get the value from a Combobox . It is easy when the Combobox is in the first created window but for example if I have two windows and the Combobox is in the second, I am not able read the value from that. For example :

from tkinter import * from tkinter import ttk def comando(): print(box_value.get()) parent = Tk() #first created window ciao=Tk() #second created window box_value=StringVar() coltbox = ttk.Combobox(ciao, textvariable=box_value, state='readonly') coltbox["values"] = ["prova","ciao","come","stai"] coltbox.current(0) coltbox.grid(row=0) Button(ciao,text="Salva", command=comando, width=20).grid(row=1) mainloop() 

2 Answers 2

You cannot have two Tk() windows. one must be Toplevel .

To get the variable you can do box_value.get()

Example of a drop down box :

class TableDropDown(ttk.Combobox): def __init__(self, parent): self.current_table = tk.StringVar() # create variable for table ttk.Combobox.__init__(self, parent)# init widget self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"]) self.current(0) # index of values for current table self.place(x = 50, y = 50, anchor = "w") # place drop down box print(self.current_table.get()) 
from tkinter import * from tkinter import ttk from tkinter import messagebox root = Tk() root.geometry("400x400") # Length and width window :D cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai")) # to create checkbox # cmb = Combobox #now we create simple function to check what user select value from checkbox def checkcmbo(): if cmb.get() == "prova": messagebox.showinfo("What user choose", "you choose prova") # if user select prova show this message elif cmb.get() == "ciao": messagebox.showinfo("What user choose", "you choose ciao") # if user select ciao show this message elif cmb.get() == "come": messagebox.showinfo("What user choose", "you choose come") elif cmb.get() == "stai": messagebox.showinfo("What user choose", "you choose stai") elif cmb.get() == "": messagebox.showinfo("nothing to show!", "you have to be choose something") cmb.place(relx="0.1",rely="0.1") btn = ttk.Button(root, text="Get Value",command=checkcmbo) btn.place(relx="0.5",rely="0.1") root.mainloop() 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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