I have a Checkbutton that I need ticked as a default when I open the window. Setting the variable to the on value doesn't seem to work, so what should I do? Here is a short, self contained example of what yields an unticked checkbox.
#!/usr/bin/python3
from tkinter import ttk
from tkinter import *
class Sizzle(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Sizzle")
self.style = ttk.Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
ifalphagrams=BooleanVar()
b=Checkbutton(self, variable=ifalphagrams, onvalue=True, offvalue=False)
b.grid(row=1,column=3 ,sticky=W)
b.select()
def main():
root = Tk()
root.geometry("700x700+700+700")
app = Sizzle(root)
root.mainloop()
if __name__ == '__main__':
main()
Most likely you're using a local variable to hold the reference to the StringVar
, and it's getting garbage collected. When you prevent the variable from being garbage-collected your code works fine:
from Tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
ifalphagrams = StringVar()
alp = Checkbutton(self, variable=ifalphagrams, onvalue='yes', offvalue='no')
alp.grid(row=1,column=3, sticky=W)
alp.select()
self.ifalphagrams = ifalphagrams
if __name__ == "__main__":
root = Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.