You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何让Python Ttk Checkbutton程序启动时默认处于选中状态?

How to Make a Ttk Checkbutton Checked by Default in Python

Hey there! The issue here is that your IntVar starts with its default value of 0, which matches your offvalue—so the checkbutton stays unselected when your app launches. Let's fix this with two straightforward approaches:

Approach 1: Set the IntVar value during initialization

You can pass the value parameter directly when creating your IntVar to set it to your onvalue (which is 1 in your code):

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
# Initialize the variable with the onvalue (1) to make the checkbutton checked by default
v = tk.IntVar(value=1)
cb = ttk.Checkbutton(root, text='Remember user', onvalue=1, offvalue=0, variable=v)
cb.pack()

root.mainloop()

Approach 2: Use the set() method after creating the variable

If you prefer to initialize the variable first and set its value later, call v.set(1) right after defining it:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
v = tk.IntVar()
# Set the variable to the onvalue to default to checked
v.set(1)
cb = ttk.Checkbutton(root, text='Remember user', onvalue=1, offvalue=0, variable=v)
cb.pack()

root.mainloop()

Why this works:

The Checkbutton uses the value of its linked variable to determine its state. Since you set onvalue=1 and offvalue=0, setting the variable to 1 tells the checkbutton to render as checked as soon as the app starts.

内容的提问来源于stack exchange,提问作者Thomas Caio

火山引擎 最新活动