Home > Net >  Unable to get selected value from Combobox in Tkinter
Unable to get selected value from Combobox in Tkinter

Time:04-12

I'm running a simple piece of code wherein whenever a value is selected from the combobox, it needs to be printed in the terminal. But whenever I select a value, after pressing the Quit Button, it's not getting printed on the terminal.

Any nudge would be appreciated.

Thank you for the help

from tkinter import *
from tkinter import ttk

win = Tk()

win.geometry("200x100")
vals = ('A','B','C','CD','E','FG')

current_var= StringVar()
cb= ttk.Combobox(win, textvariable = current_var)
cb['values']= vals
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)
IP = current_var.get()
Button(win, text="Quit", command=win.destroy).pack()
win.mainloop()
print(IP)

CodePudding user response:

If you want the quit button to print the value then change it to something like this.

from tkinter import *
from tkinter import ttk


def get_value():
    IP = current_var.get()
    print(IP)
    win.destroy()
    
win = Tk()

win.geometry("200x100")
vals = ('A','B','C','CD','E','FG')

current_var= StringVar()
cb= ttk.Combobox(win, textvariable = current_var)
cb['values']= vals
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)
IP = current_var.get()
Button(win, text="Quit", command= get_value).pack()
win.mainloop()
print(IP)

CodePudding user response:

@Rory's answer isn't quite right because the final print(IP) is simply printing a newline (which he probably didn't notice). To fix that the get_value() callback function should declare global IP so IP is no longer a variable local to the function and its value can be accessed outside the function.

The code below illustrates this and also follows the PEP 8 - Style Guide for Python Code guidelines more closely than what's in your question.

import tkinter as tk  # PEP 8 advises avoiding `import *`
import tkinter.ttk as ttk


def get_value():
    global IP
    IP = current_var.get()
    win.destroy()


win = tk.Tk()
win.geometry("200x100")
vals = 'A','B','C','CD','E','FG'
current_var = tk.StringVar(win)
cb = ttk.Combobox(win, textvariable=current_var, values=vals, state='readonly')
cb.pack(fill='x', padx= 5, pady=5)
tk.Button(win, text="Quit", command=get_value).pack()
win.mainloop()
print(IP)

CodePudding user response:

You get the value just after cb is created and the value should be empty string because there is no item is selected at that time. You need to get the value after an item is selected.

One of the way is to move the line IP = current_var.get() after win.mainloop():

from tkinter import *
from tkinter import ttk

win = Tk()
win.geometry("200x100")

vals = ('A','B','C','CD','E','FG')

current_var = StringVar()
cb= ttk.Combobox(win, textvariable=current_var)
cb['values'] = vals
cb['state'] = 'readonly'
cb.pack(fill='x', padx=5, pady=5)

Button(win, text="Quit", command=win.destroy).pack()

win.mainloop()

IP = current_var.get()
print(IP)
  • Related