13

I am making a Menu using Tkinter, but I wanted to put "add_checkbutton" instead of "add_command" into the menu options, but problem is: how i deselect/select a checkbox?

menu = Menu(parent)

parent.config(menu=menu)

viewMenu = Menu(menu)

menu.add_cascade(label="View", menu=viewMenu)
viewMenu.add_command(label = "Show All", command=self.showAllEntries)
viewMenu.add_command(label="Show Done", command= self.showDoneEntries)
viewMenu.add_command(label="Show Not Done", command = self.showNotDoneEntries)
nbro
  • 15,395
  • 32
  • 113
  • 196
itsaboutcode
  • 24,525
  • 45
  • 110
  • 156

2 Answers2

26

You need to associate a variable with the checkbutton item(s), then set the variable to cause the item to be checked or unchecked. For example:

import tkinter as tk

parent = tk.Tk()

menubar = tk.Menu(parent)
show_all = tk.BooleanVar()
show_all.set(True)
show_done = tk.BooleanVar()
show_not_done = tk.BooleanVar()

view_menu = tk.Menu(menubar)
view_menu.add_checkbutton(label="Show All", onvalue=1, offvalue=0, variable=show_all)
view_menu.add_checkbutton(label="Show Done", onvalue=1, offvalue=0, variable=show_done)
view_menu.add_checkbutton(label="Show Not Done", onvalue=1, offvalue=0, variable=show_not_done)
menubar.add_cascade(label='View', menu=view_menu)
parent.config(menu=menubar)

parent.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Hi there, thanks for your reply. I am getting little problem in executing this because i am getting error about tk.BooleanVar() – itsaboutcode Oct 15 '10 at 16:56
  • 1
    @itsaboutcode: probably because you are importing Tkinter in a different way. It looks like you are importing everything from Tkinter so you can probably change the code to just "BooleanVar()". – Bryan Oakley Oct 15 '10 at 17:26
  • is there a way to make only one checkbutton selectable? – coder_not_found Apr 18 '21 at 09:27
  • 1
    @coder_not_found: yes: use radiobuttons instead. Radiobuttons are specifically designed for an exclusive choice (pick one of N). – Bryan Oakley Apr 18 '21 at 13:46
0

here I try to solve your question and I found a logic. Hope so it will help u :)

from tkinter import *
root=Tk()
root.geometry("300x300")
var1='button1'
var2='button2'

def fun(value):
    if value=="button1":
        testmenu.entryconfigure("button1",background="light blue")
        testmenu.entryconfigure("button2", background="#ede8ec")
        label.config(text="Afridi-1")
    if value=="button2":
        testmenu.entryconfigure("button2",background="light blue")
        testmenu.entryconfigure("button1", background="#ede8ec")
        label.config(text="Afridi-2")
mainmenu=Menu(root)
root.config(menu=mainmenu)
testmenu=Menu(mainmenu,tearoff=False,background="#ede8ec")
mainmenu.add_cascade(label="Test",menu=testmenu)
testmenu.add_command(label="button1",command=lambda :fun(var1))
testmenu.add_command(label="button2",command=lambda :fun(var2))
label=Label(text="")
label.pack(pady=125)
root.mainloop()