Rob Lasch
Rob Lasch

Reputation: 107

How do you get tkinter dropdown menu to open on top of other windows?

I am running this in Pycharm, and I can't get this dropdown to open on top of other windows. I would also like to center the dropdown menu in the center of the screen.

from tkinter import *

def dropdown_menu(menu_list):
    root = Tk()
    root.title('Process Mode')

    # Create a Tkinter variable
    tkvar = StringVar(root)

    def on_selection(value):
        global dropdown_choice
        dropdown_choice = value
        root.destroy()

    popupMenu = OptionMenu(root, tkvar, *menu_list, command=on_selection)
    Label(root, text='Choose Mode').grid(row=2, column=2)
    popupMenu.grid(row=2, column=2)
    popupMenu.config(width=20, height=2)

    # on change dropdown value
    def change_dropdown(*args):
        global dropdown
        dropdown = str(tkvar.get())

    # link function to change dropdown
    tkvar.trace('w', change_dropdown)

    root.mainloop()

    return dropdown_choice

options = ['1', '2', '3']

selection = dropdown_menu(options)

Upvotes: 1

Views: 70

Answers (2)

acw1668
acw1668

Reputation: 47085

You can make the window the topmost window using .attributes() and place the window at the center of screen using TCL command PlaceWindow:

def dropdown_menu(menu_list):
    ...

    # place the window at the center of screen
    root.call("::tk::PlaceWindow", root._w, "center")
    # make the window the topmost window
    root.attributes("-topmost", 1)

    root.mainloop()

    ...

Upvotes: 2

NULL
NULL

Reputation: 108

from tkinter import *

def dropdown_menu(menu_list):
    root = Tk()
    root.title('Process Mode')
    root.focus()
    
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    
    appWidth = 200
    appHeight = 100
    
    root.geometry(f'{appWidth}x{appHeight}+{round((screen_width-appWidth)/2)}+{round((screen_height-appHeight)/2)}')

    tkvar = StringVar(root)
    tkvar.set('Choose Mode')

    def on_selection(value):
        global dropdown_choice
        dropdown_choice = value
        root.destroy()

    popupMenu = OptionMenu(root, tkvar, *menu_list, command=on_selection)
    popupMenu.grid(row=2, column=2)
    popupMenu.config(width=20, height=2)

    root.mainloop()

    return dropdown_choice

options = ['1', '2', '3']

selection = dropdown_menu(options)

root.focus() should make the window when it's called the top window

round((screen_width-appWidth)/2)} this is used to get half of the screen's width

tkvar.set('Choose Mode') this is used to display the text (instead of using a label which can get confusing)

hope it helps :)

Upvotes: 1

Related Questions