i am new to Python. And I am trying to make a drop down menu which will have some options (eg 4 options). I also need a Ok button in the same window. The user needs to select an option and click on "Ok". I need only single selection. When the user clicks Ok after selection, the selected option should be put in an variable.
Please help me in this . It will be great if this can be done in Tkinter. :)

Dani AI

Generated

If you want a single-selection dropdown with an OK button in Tkinter, prefer ttk.Combobox. Set it to state="readonly" so users cannot type arbitrary values. On OK, read the StringVar (or the widget via combobox.get()), store it in a normal Python variable, and close the window so the script can continue.

Example:

import tkinter as tk
from tkinter import ttk

def on_ok():
    root.selected = choice.get()  # capture selection in a normal attribute
    root.destroy()                # close window to continue execution

root = tk.Tk()
choice = tk.StringVar(value="Option 1")

combo = ttk.Combobox(root, textvariable=choice,
                     values=["Option 1", "Option 2", "Option 3", "Option 4"],
                     state="readonly")
combo.pack(padx=10, pady=10)

ttk.Button(root, text="OK", command=on_ok).pack(padx=10, pady=5)
root.mainloop()

# after the window closes, the selected option is in a plain variable
selected_option = getattr(root, "selected", None)
print("You chose:", selected_option)

Notes:

  • Use combo.current(0) if you want to set the default by index instead of value.
  • For immediate reactions without an OK button, bind "<<ComboboxSelected>>" to a callback.
  • Official docs: ttk.Combobox in tkinter and Tk’s ttk::combobox event details.

Recommended Answers

All 4 Replies

Post the code you have so far along with any problems.

use GUI toolkit. If you go for wxPython there is wxComboBox as one of options

You can use Tkinter that comes with the Python installation:

# using Tkinter's Optionmenu() as a combobox

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def select():
    sf = "value is %s" % var.get()
    root.title(sf)
    # optional
    color = var.get()
    root['bg'] = color


root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
root.title("tk.Optionmenu as combobox")

var = tk.StringVar(root)
# initial value
var.set('red')

choices = ['red', 'green', 'blue', 'yellow','white', 'magenta']
option = tk.OptionMenu(root, var, *choices)
option.pack(side='left', padx=10, pady=10)

button = tk.Button(root, text="check value slected", command=select)
button.pack(side='left', padx=20, pady=10)

root.mainloop()

simple wxPyCode that does nothing, just a display!
import wx

class wxDemo(wx.Frame):
    def __init__(self, parent): 
        wx.Frame.__init__(self, parent, title='Demo Frame')
        self.panel = wx.Panel(self, -1)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.combo = wx.ComboBox(self.panel, choices=['Moja', 'Mbili', 'Tatu', 'Nne', 'Tano'])
        self.text = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_MULTILINE)
        
        self.sizer.Add(self.combo, 0, wx.EXPAND)
        self.sizer.Add(self.text, 1, wx.EXPAND)
        
        self.panel.SetSizer(self.sizer)
        self.panel.Layout()
        
app = wx.App()
fr = wxDemo(None)
fr.Show()
app.MainLoop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.