Retrieving And Using A Tkinter Combobox Selection
I am putting together a GUI for a customized calculator that automatically converts certain units of measurements into other units of measurement. I want to return the actual text
Solution 1:
You should retrieve the content of comboARU
using get()
function as follows:
defcallback(eventObject):
print(comboARU.get())
Solution 2:
you can retrieve the value of the Combobox directly off the event object by eventObject.widget.get() .
import tkinter as tk
from tkinter.ttk import *
master = tk.Tk()
master.title("Gas Calculator")
v = tk.IntVar()
combo = Combobox(master)
defcallback(eventObject):
# you can also get the value off the eventObjectprint(eventObject.widget.get())
# to see other information also available on the eventObjectprint(dir(eventObject))
comboARU = Combobox(master)
comboARU['values']= ("Acres", "Ft^2")
comboARU.current(0) #set the selected item
comboARU.grid(row=3, column=2)
comboARU.bind("<<ComboboxSelected>>", callback)
master.mainloop()
Solution 3:
If you want be get be able to use the default value set with comboAru.current(0)
, event handling doesn't work, I find it works best to get the combobox value when pressing an OK button, and if you want to get the value and use it afterwards, it's best to create a class, avoiding global variables (because the class instance and it's variables remain after tkinter window is destroyed) (based on answer https://stackoverflow.com/a/49036760/12141765).
import tkinter as tk # Python 3.xfrom tkinter import ttk
classComboboxSelectionWindow():
def__init__(self, master):
self.master=master
self.entry_contents=None
self.labelTop = tk.Label(master,text = "Select one of the following")
self.labelTop.place(x = 20, y = 10, width=140, height=10)
self.comboBox_example = ttk.Combobox(master,values=["Choice 1","Second choice","Something","Else"])
self.comboBox_example.current(0)
self.comboBox_example.place(x = 20, y = 30, width=140, height=25)
self.okButton = tk.Button(master, text='OK',command = self.callback)
self.okButton.place(x = 20, y = 60, width=140, height=25)
defcallback(self):
""" get the contents of the Entry and exit
"""
self.comboBox_example_contents=self.comboBox_example.get()
self.master.destroy()
defComboboxSelection():
app = tk.Tk()
app.geometry('180x100')
Selection=ComboboxSelectionWindow(app)
app.mainloop()
print("Selected interface: ", Selection.comboBox_example_contents)
return Selection.comboBox_example_contents
print("Tkinter combobox text selected =", ComboboxSelection())
Post a Comment for "Retrieving And Using A Tkinter Combobox Selection"