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.
JavaScript
x
22
22
1
from tkinter import *
2
root = Tk()
3
4
5
display_text=StringVar()
6
e1=Entry(root, textvariable=display_text, width=42)
7
e1.grid(row=0, column=1)
8
9
def OptionMenu_Select():
10
display_text.set(var.get())
11
12
Menu = {"Pho bo":"$3.50", "Chao ga":"$3.99", "pho xao":"$4.10", "Com rang":"$3.80"}
13
choices = [m + " " + Menu[m] for m in Menu]
14
15
var=StringVar()
16
var.set(choices[0])
17
display_text.set(choices[0])
18
popupMenu = OptionMenu(root, var, *choices, command = OptionMenu_Select)
19
popupMenu.grid(row=1, column=1)
20
21
root.mainloop()
22
Advertisement
Answer
If you run the code in a terminal, then you should see there is exception when an item is selected in the option menu:
JavaScript
1
2
1
TypeError: OptionMenu_Select() takes 0 positional arguments but 1 was given
2
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:
JavaScript
1
5
1
def OptionMenu_Select(val):
2
#display_text.set(var.get())
3
# just use the passed argument
4
display_text.set(val)
5