OptionMenu widget not updating when StringVar is changed until hovered

Viewed 213

I need a menu that can respond to items being clicked by running code then switch the text back to a default text.

Currently, my implementation works but the default text is only displayed when the cursor hovers over the menu after clicking.

I have searched but I could not find anything related to this problem, although maybe that is because I am unsure as to what exactly is causing this.

Here is the code to reproduce this behaviour:

from tkinter import *

root = Tk()

default_text = 'select an item'

def thing_selected(self, *args):
    #other stuff happens here
    var.set(default_text)

var = StringVar(root)
var.set(default_text)
var.trace('w', thing_selected)

menu = OptionMenu(root, var, *['Pizza','Lasagne','Fries','Fish'])
menu.pack()

root.mainloop()

Here is a gif representing the outcome: gif

I would expect the text at the top to be updated instantaneously, but it only updates when the cursor has hovered over the widget

I am looking for some way to trigger a hover event on the widget or I am open to suggestions for any other methods of accomplishing this.

1 Answers

You could take a different route and use the command attribute of the OptionMenu:

import tkinter as tk

root = tk.Tk()

default_text = 'select an item'

def thing_selected(selected):
    #other stuff happens here
    print(var.get())
    var.set(default_text)
    print(var.get())

var = tk.StringVar()
var.set(default_text)

options = ['Pizza','Lasagne','Fries','Fish']
menu = tk.OptionMenu(root, var, *options, command = thing_selected)
menu.pack()

root.mainloop()
Related