Search code examples
pythontkintercomboboxttk

How do I get an attribute from a Combobox and put it into a variable?


I'm making a project in Tkinter Python and I want users to select an attribute from a Combobox widget and press a button and that attribute will be stored in a variable. I've searched all over the web, but I can't make heads or tails of the code and have no idea how to store this attribute. Can someone tell me how to do this

I've tried the .get thing... (module? widget?) but that is not working and as I said, the internet ain't no help.

This is my basic code with the window and the Combobox:

from tkinter import *
from tkinter import ttk

master = Tk()

ver = ttk.Combobox(master, state="readonly", values=["test1", "test2"]).pack()
Button(master, text="Run").pack()

master.mainloop()

I want to be able to store the selected item in the Combobox and put it in a variable.


Solution

  • pack returns None if you want to assign to a variable, you must do it on a separate line.
    If you want action, Button requires a command key word arg to which you assign a callback.

    After you have fixed the mistakes, you can use the get method on the Combobox:

    import tkinter as tk
    from tkinter import ttk
    
    
    def print_selected():
        print(combo.get())
    
    
    master = tk.Tk()
    
    combo = ttk.Combobox(master, state="readonly", values=["test1", "test2"])
    combo.pack()
    tk.Button(master, text="Run", command=print_selected).pack()
    
    master.mainloop()