Home > Enterprise >  Can't not update the textbox when clicked the optionmenu
Can't not update the textbox when clicked the optionmenu

Time:04-29

I'm trying to display my selection in the optionmenu to the textbox. Could anyone help me with this one? when I clicked one option in the optionmenu, the textbox didn't update. Here is my code.

from tkinter import *
root = Tk()


display_text=StringVar()
e1=Entry(root, textvariable=display_text, width=42)
e1.grid(row=0, column=1)

def OptionMenu_Select(): 
   display_text.set(var.get())  

Menu = {"Pho bo":"$3.50", "Chao ga":"$3.99", "pho xao":"$4.10", "Com rang":"$3.80"}
choices = [m   "  "   Menu[m] for m in Menu]  

var=StringVar()
var.set(choices[0])  
display_text.set(choices[0]) 
popupMenu = OptionMenu(root, var, *choices, command = OptionMenu_Select)
popupMenu.grid(row=1, column=1)

root.mainloop()

CodePudding user response:

If you run the code in a terminal, then you should see there is exception when an item is selected in the option menu:

TypeError: OptionMenu_Select() takes 0 positional arguments but 1 was given

It is because the callback of command option of OptionMenu expects an argument, the selected item, but your function does not have argument.

Just modify the function as below:

def OptionMenu_Select(val):
   #display_text.set(var.get())
   # just use the passed argument
   display_text.set(val)
  • Related