Changing the options of a OptionMenu when clicking a Button
I modified your script to demonstrate how to do this:
import Tkinter as tk
root = tk.Tk()
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
def refresh():
# Reset var and delete all old options
var.set('')
network_select['menu'].delete(0, 'end')
# Insert list of new options (tk._setit hooks them up to var)
new_choices = ('one', 'two', 'three')
for choice in new_choices:
network_select['menu'].add_command(label=choice, command=tk._setit(var, choice))
network_select = tk.OptionMenu(root, var, *choices)
network_select.grid()
# I made this quick refresh button to demonstrate
tk.Button(root, text='Refresh', command=refresh).grid()
root.mainloop()
As soon as you click the "Refresh" button, the options in network_select are cleared and the ones in new_choices are inserted. How to set an optionmenu with a button click tkinter
You had your own answer in your code already (line 3) (:
You can make a function that is called when the reset button is hit, which will reset genderVar to genderList[0]. This is what it will look like: (Keep in mind I changed the name of the window to Root for testing purposes)
def reset():
global genderVar
genderVar.set(genderList[0])
root=tk.Tk()
genderList = ["Gender", "Male", "Female", "Other"]
genderVar = tk.StringVar()
genderVar.set(genderList[0])
genderO = tk.OptionMenu(root, genderVar, *genderList)
genderO.config(width = 8)
genderO.pack()
tk.Button(root,text="Reset",command=reset).pack()
root.mainloop()
Changing one OptionMenu changes the second one
I guess the function update_file_list_selection() and lambda function is implemented badly.That is a correct guess.
The reason is a common problem with using lambda
- when you do command=lambda value=x: file_selection.variable_file.set(value)
, the value of file_selection
won't be the value from the loop, it will end up being the value of the final time that variable was set. You can solve this by binding the value to the lambda
as a default argument:
self.menu.add_command(label=x, command=lambda value=x, fs=file_selection: fs.variable_file.set(value))
The above will make sure that inside the lambda
body, fs
will be set to the value of file_selection
at the time the menu item is made rather than the value at the time the item is selected.You'll still end up with OptionMenu
items that don't behave exactly the same as normal OptionMenu
items, but in this specific example that doesn't seem to matter since you don't have a command
associated with the OptionMenu
as a whole.
How to change a buttons state from disabled to active when an option is selected in an OptionMenu Tkinter
Change your function to this:
def changeState():
pick = choose.get()
if (pick == "op2"):
button['state'] = ACTIVE #means active state
button.config(text = "ACTIVE")
else:
button['state'] = DISABLED #means disabled state
button.config(text = "Disabled")
Also your not calling your function, so to call it and make the effect active, add a command argument onto your optionmenu, like:options = OptionMenu(app, choose, "op1", "op2",command=lambda _:changeState())
Using lambda _:
because optionmenu command expect a tkinter variable to be passed on, so as to avoid that. You could also have a parameter for your function, but if your calling your function somewhere else, your gonna have to pass in a argument or your could also use parameter like point=None
and get rid of the lambda
.Hope this cleared the errors, do let me know if any doubts.
Cheers
How to change the values in tkinter's OptionMenu?
tk.OptionMenu
has a Menu
widget in it.
If you want to add some values,you could use add_command
:
for i in ["C","D"]:
newMenu['menu'].add_command(label=i)
If you want to remove some values, use delete
:
newMenu['menu'].delete("0",tk.END) # this will remove all the values
@acw1668 pointed out a big problem in my code,if you want to also bind command and change the
clicked
variable.Recommend this(acw1668 sugguests):
for i in ["C", "D"]:
newMenu['menu'].add_command(label=i, command=tk._setit(clicked, i, doSomething))
this also could do but don't recommend:for i in ["C", "D"]:
newMenu['menu'].add_command(label=i, command=lambda i=i:clicked.set(i) or doSomething(i))
Updating OptionMenu from List
The options in an OptionMenu are not bound to the list from which they are created. Therefore, changing the list does not change the OptionMenu, you'll have to update it yourself.
You can do that by getting the OptionMenu's menu
, and add commands to that. The following example shows how to do this (based on this answer).
It shows that, even though the self.options
list is appended with an option using the 'Add option to list' button, the OptionMenu does not change automatically. To update the OptionMenu, you can use the 'Update option menu' button for this, which calls self.update_option_menu
. This function deletes all options from the OptionMenu, and inserts a new one for each item in self.options
.
import Tkinter as tk
class App():
def __init__(self, parent):
self.parent = parent
self.options = ['one', 'two', 'three']
self.om_variable = tk.StringVar(self.parent)
self.om_variable.set(self.options[0])
self.om_variable.trace('w', self.option_select)
self.om = tk.OptionMenu(self.parent, self.om_variable, *self.options)
self.om.grid(column=0, row=0)
self.label = tk.Label(self.parent, text='Enter new option')
self.entry = tk.Entry(self.parent)
self.button = tk.Button(self.parent, text='Add option to list', command=self.add_option)
self.label.grid(column=1, row=0)
self.entry.grid(column=1, row=1)
self.button.grid(column=1, row=2)
self.update_button = tk.Button(self.parent, text='Update option menu', command=self.update_option_menu)
self.update_button.grid(column=0, row=2)
def update_option_menu(self):
menu = self.om["menu"]
menu.delete(0, "end")
for string in self.options:
menu.add_command(label=string,
command=lambda value=string: self.om_variable.set(value))
def add_option(self):
self.options.append(self.entry.get())
self.entry.delete(0, 'end')
print self.options
def option_select(self, *args):
print self.om_variable.get()
root = tk.Tk()
App(root)
root.mainloop()
How can I make a Tkinter OptionMenu not change the text when an option is selected?
An option menu is nothing but a Menubutton
with a Menu
, and some special code specifically to change the text of the button. If you don't need that feature, just create your own with a Menubutton
and Menu
.
Example:
import tkinter as tk
root = tk.Tk()
var = tk.StringVar()
label = tk.Label(root, textvariable=var)
menubutton = tk.Menubutton(root, text="Select an option",
borderwidth=1, relief="raised",
indicatoron=True)
menu = tk.Menu(menubutton, tearoff=False)
menubutton.configure(menu=menu)
menu.add_radiobutton(label="One", variable=var, value="One")
menu.add_radiobutton(label="Two", variable=var, value="Two")
menu.add_radiobutton(label="Three", variable=var, value="Three")
label.pack(side="bottom", fill="x")
menubutton.pack(side="top")
root.mainloop()
How to clear or refresh OptionMenu after submit button clicked
hi the problem is here
#Name dropdown menu
Names1A = ["Jarrod","Jeremy", "Joe", "John", "Rob", "Spencer"]
Label(master, text="Your Name").grid(row=0)
named = StringVar()
named.set("Choose Name")
drop = OptionMenu(master,named, *Names1A)
drop.grid(row=0, column=1)
but the correct way is to add a StringVar() to OptionMenu and after add all your voices.# Name dropdown menu
Label(master, text="Your Name").grid(row=0)
named = StringVar()
drop = OptionMenu(master,named, "Choose Name","Jarrod","Jeremy", "Joe", "John", "Rob", "Spencer")
named.set("Choose Name")
drop.grid(row=0, column=1)
and when you submit,you can set your prefer value using set method of StringVar()entry3.delete(0, END)
entry4.delete(0, END)
named.set("Choose Name")
reasond.set("Choose Reason")
How to get text from an OptionMenu when I press a button (Tkinter)
this was the source of the error:
def get_optionMenu_selection():
value = callback(None) ### this returns None
print(value)
in fact, you don't need the callback function because you are using a button. you only need to pass the variable to the get_optionMenu_selection
function.from tkinter import *
from functools import partial
root = Tk()
root.geometry('300x300')
menubar = Menu(root)
root.config(menu=menubar)
###the other function was removed
def get_optionMenu_selection(variable): ###this changed
print(variable.get())
def upload_months():
months = ["January", "Feb","Mar"]
variable = StringVar(root)
variable.set('Choose')
w = OptionMenu(root, variable, *months)
B = Button(root, text ="Send", command = partial(get_optionMenu_selection, variable)) ###this changed
w.place(x=20, y=10)
B.place(x= 105, y=11)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Upload months", command=upload_months)
filemenu.add_command(label="Open")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.mainloop()
Related Topics
Loading JSONl File as JSON Objects
Joining Pairs of Elements of a List
Can't Get Python to Import from a Different Folder
Round Up to Second Decimal Place in Python
Python: Why Does ("Hello" Is "Hello") Evaluate as True
Pandas - Filter Dataframe by Another Dataframe by Row Elements
Strip/Trim All Strings of a Dataframe
Multiprocessing.Pool Makes Numpy Matrix Multiplication Slower
Plotting Multiple Lines, in Different Colors, with Pandas Dataframe
How to Save Final Model Using Keras
How to Set Opacity of Background Colour of Graph with Matplotlib
Import Text to Pandas with Multiple Delimiters
Scale Matplotlib.Pyplot.Axes.Scatter Markersize by X-Scale
Multiple Plots in One Figure in Python
Create Spark Dataframe. Can Not Infer Schema for Type
How to Align Gridlines for Two Y-Axis Scales Using Matplotlib