Home > Net >  Can I make the checkbutton already checked when I open the window in tkinter menubar in Python?
Can I make the checkbutton already checked when I open the window in tkinter menubar in Python?

Time:10-29

I was trying to make a application by tkinter, and I wanted to make a checkbutton in menubar. However, I don't know how to make the checkbutton already checked when I run the code.

Here's my code

import tkinter as tk
def func():
    #some code here
var = tk.BooleanVar
win = tk.Tk()
menubar = tk.Menu(win)
optmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Options', menu=optmenu)
optmenu.add_checkbutton(label='xyz', variable=var, onvalue=1, offvalue=0, command=func)
win.config(menu=menubar)
win.mainloop()

CodePudding user response:

use this code below:

import tkinter as tk
def func():
    pass
    #some code here

win = tk.Tk()
var = tk.StringVar(win,'on')
menubar = tk.Menu(win)
optmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Options', menu=optmenu)
optmenu.add_checkbutton(label='xyz', variable=var, onvalue='on', offvalue='off', command=func)

win.config(menu=menubar)
win.mainloop()

have fun :)

  • Related