0
点赞
收藏
分享

微信扫一扫

PYTHON tkinter模块-20

kolibreath 2025-11-23 阅读 151

Checkbutton(复选框)是Tkinter中用于创建多选选项的组件,允许用户选择多个选项。

基本用法

1. 导入和基本创建

import tkinter as tk
from tkinter import messagebox

# 创建主窗口
root = tk.Tk()
root.title("Checkbutton组件详解")
root.geometry("500x400")

2. 创建基本Checkbutton

# 创建BooleanVar来跟踪复选框状态
var1 = tk.BooleanVar()
var2 = tk.BooleanVar()

# 创建Checkbutton
check1 = tk.Checkbutton(root, text="选项1", variable=var1)
check1.pack(pady=10)

check2 = tk.Checkbutton(root, text="选项2", variable=var2)
check2.pack(pady=10)

# 显示选择结果的按钮
def show_selection():
    selections = []
    if var1.get():
        selections.append("选项1")
    if var2.get():
        selections.append("选项2")
    
    if selections:
        messagebox.showinfo("选择结果", f"你选择了: {', '.join(selections)}")
    else:
        messagebox.showinfo("选择结果", "你没有选择任何选项")

tk.Button(root, text="显示选择", command=show_selection).pack(pady=20)

root.mainloop()

Checkbutton的完整参数和功能

示例1:Checkbutton全面展示

import tkinter as tk
from tkinter import ttk

class CheckbuttonComprehensive:
    def __init__(self, root):
        self.root = root
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        self.root.title("Checkbutton组件全面展示")
        self.root.geometry("600x500")
        
        # 创建主Frame
        main_frame = tk.Frame(self.root, bg="#f0f0f0", padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 1. 基本Checkbutton示例
        self.create_basic_checkbuttons(main_frame)
        
        # 2. 不同状态的Checkbutton
        self.create_state_checkbuttons(main_frame)
        
        # 3. 带命令的Checkbutton
        self.create_command_checkbuttons(main_frame)
        
        # 4. 样式化Checkbutton
        self.create_styled_checkbuttons(main_frame)
        
        # 5. 实际应用示例
        self.create_practical_example(main_frame)
        
    def create_basic_checkbuttons(self, parent):
        """创建基本Checkbutton示例"""
        section_frame = tk.LabelFrame(parent, text="1. 基本Checkbutton示例", 
                                     padx=10, pady=10, bg="white")
        section_frame.pack(fill=tk.X, pady=10)
        
        # 使用BooleanVar
        self.var1 = tk.BooleanVar()
        check1 = tk.Checkbutton(section_frame, text="选项1 (BooleanVar)", 
                               variable=self.var1, bg="white")
        check1.pack(anchor="w", pady=2)
        
        # 使用IntVar (0=未选中, 1=选中)
        self.var2 = tk.IntVar()
        check2 = tk.Checkbutton(section_frame, text="选项2 (IntVar)", 
                               variable=self.var2, bg="white")
        check2.pack(anchor="w", pady=2)
        
        # 使用StringVar
        self.var3 = tk.StringVar()
        self.var3.set("off")  # 默认值
        check3 = tk.Checkbutton(section_frame, text="选项3 (StringVar)", 
                               variable=self.var3, 
                               onvalue="on", offvalue="off", bg="white")
        check3.pack(anchor="w", pady=2)
        
        # 显示状态按钮
        show_btn = tk.Button(section_frame, text="显示所有状态", 
                            command=self.show_basic_states)
        show_btn.pack(anchor="w", pady=5)
        
    def create_state_checkbuttons(self, parent):
        """创建不同状态的Checkbutton"""
        section_frame = tk.LabelFrame(parent, text="2. 不同状态的Checkbutton", 
                                     padx=10, pady=10, bg="white")
        section_frame.pack(fill=tk.X, pady=10)
        
        # 正常状态
        self.normal_var = tk.BooleanVar(value=True)
        normal_check = tk.Checkbutton(section_frame, text="正常状态", 
                                     variable=self.normal_var, state="normal", bg="white")
        normal_check.pack(anchor="w", pady=2)
        
        # 禁用状态
        self.disabled_var = tk.BooleanVar(value=True)
        disabled_check = tk.Checkbutton(section_frame, text="禁用状态", 
                                       variable=self.disabled_var, state="disabled", bg="white")
        disabled_check.pack(anchor="w", pady=2)
        
        # 只读状态(看起来正常但不能修改)
        self.readonly_var = tk.BooleanVar(value=False)
        readonly_check = tk.Checkbutton(section_frame, text="只读状态", 
                                       variable=self.readonly_var, state="readonly", bg="white")
        readonly_check.pack(anchor="w", pady=2)
        
        # 状态控制按钮
        state_frame = tk.Frame(section_frame, bg="white")
        state_frame.pack(fill=tk.X, pady=5)
        
        tk.Button(state_frame, text="启用所有", command=self.enable_all).pack(side="left", padx=2)
        tk.Button(state_frame, text="禁用所有", command=self.disable_all).pack(side="left", padx=2)
        tk.Button(state_frame, text="切换只读", command=self.toggle_readonly).pack(side="left", padx=2)
        
    def create_command_checkbuttons(self, parent):
        """创建带命令的Checkbutton"""
        section_frame = tk.LabelFrame(parent, text="3. 带命令的Checkbutton", 
                                     padx=10, pady=10, bg="white")
        section_frame.pack(fill=tk.X, pady=10)
        
        # 实时响应
        self.command_var = tk.BooleanVar()
        command_check = tk.Checkbutton(section_frame, text="实时响应复选框", 
                                      variable=self.command_var, 
                                      command=self.on_command_change, bg="white")
        command_check.pack(anchor="w", pady=2)
        
        # 命令结果显示
        self.command_result = tk.Label(section_frame, text="状态: 未选中", 
                                      bg="white", fg="red")
        self.command_result.pack(anchor="w", pady=5)
        
        # 带参数的命令
        self.param_vars = []
        param_frame = tk.Frame(section_frame, bg="white")
        param_frame.pack(fill=tk.X, pady=5)
        
        tk.Label(param_frame, text="带参数命令:", bg="white").pack(anchor="w")
        
        for i in range(3):
            var = tk.BooleanVar()
            self.param_vars.append(var)
            check = tk.Checkbutton(param_frame, text=f"选项 {i+1}", 
                                  variable=var,
                                  command=lambda idx=i: self.on_param_change(idx), 
                                  bg="white")
            check.pack(anchor="w", pady=1)
            
    def create_styled_checkbuttons(self, parent):
        """创建样式化Checkbutton"""
        section_frame = tk.LabelFrame(parent, text="4. 样式化Checkbutton", 
                                     padx=10, pady=10, bg="white")
        section_frame.pack(fill=tk.X, pady=10)
        
        # 不同颜色
        self.color_var = tk.BooleanVar()
        color_check = tk.Checkbutton(section_frame, text="红色复选框", 
                                    variable=self.color_var,
                                    bg="white", fg="red", 
                                    selectcolor="lightcoral",
                                    activebackground="lightpink",
                                    activeforeground="darkred")
        color_check.pack(anchor="w", pady=2)
        
        # 不同字体
        self.font_var = tk.BooleanVar()
        font_check = tk.Checkbutton(section_frame, text="粗体复选框", 
                                   variable=self.font_var,
                                   bg="white", font=("Arial", 10, "bold"))
        font_check.pack(anchor="w", pady=2)
        
        # 带图标的Checkbutton
        self.icon_var = tk.BooleanVar()
        icon_check = tk.Checkbutton(section_frame, text="⭐ 带图标的复选框", 
                                   variable=self.icon_var, bg="white")
        icon_check.pack(anchor="w", pady=2)
        
        # 指示器位置
        self.indicator_var = tk.BooleanVar()
        indicator_check = tk.Checkbutton(section_frame, text="指示器在右侧", 
                                        variable=self.indicator_var,
                                        indicatoron=False,  # 使用按钮样式
                                        bg="white")
        indicator_check.pack(anchor="w", pady=2)
        
    def create_practical_example(self, parent):
        """创建实际应用示例"""
        section_frame = tk.LabelFrame(parent, text="5. 实际应用示例", 
                                     padx=10, pady=10, bg="white")
        section_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 设置选择
        tk.Label(section_frame, text="选择你的兴趣:", bg="white", 
                font=("Arial", 10, "bold")).pack(anchor="w", pady=5)
        
        self.interests = []
        interests_list = ["编程", "阅读", "音乐", "运动", "旅游", "摄影", "美食", "游戏"]
        
        for interest in interests_list:
            var = tk.BooleanVar()
            self.interests.append((interest, var))
            check = tk.Checkbutton(section_frame, text=interest, variable=var, bg="white")
            check.pack(anchor="w", pady=1)
            
        # 选择结果
        result_btn = tk.Button(section_frame, text="显示选择的兴趣", 
                              command=self.show_interests)
        result_btn.pack(anchor="w", pady=10)
        
        self.interest_result = tk.Label(section_frame, text="", bg="white", 
                                       wraplength=400, justify="left")
        self.interest_result.pack(anchor="w", fill=tk.X)
        
    def show_basic_states(self):
        """显示基本Checkbutton状态"""
        result = f"""
        选项1 (BooleanVar): {self.var1.get()}
        选项2 (IntVar): {self.var2.get()}
        选项3 (StringVar): {self.var3.get()}
        """
        print(result)
        
    def on_command_change(self):
        """命令回调函数"""
        state = "选中" if self.command_var.get() else "未选中"
        color = "green" if self.command_var.get() else "red"
        self.command_result.config(text=f"状态: {state}", fg=color)
        
    def on_param_change(self, index):
        """带参数的命令回调"""
        state = "选中" if self.param_vars[index].get() else "未选中"
        print(f"选项 {index+1} 被{state}")
        
    def enable_all(self):
        """启用所有Checkbutton"""
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.LabelFrame):
                for child in widget.winfo_children():
                    if isinstance(child, tk.Checkbutton):
                        child.config(state="normal")
                        
    def disable_all(self):
        """禁用所有Checkbutton"""
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.LabelFrame):
                for child in widget.winfo_children():
                    if isinstance(child, tk.Checkbutton):
                        child.config(state="disabled")
                        
    def toggle_readonly(self):
        """切换只读状态"""
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.LabelFrame):
                for child in widget.winfo_children():
                    if isinstance(child, tk.Checkbutton) and "只读状态" in child.cget("text"):
                        current_state = child.cget("state")
                        new_state = "normal" if current_state == "readonly" else "readonly"
                        child.config(state=new_state)
                        
    def show_interests(self):
        """显示选择的兴趣"""
        selected = [interest for interest, var in self.interests if var.get()]
        if selected:
            result = f"你选择的兴趣: {', '.join(selected)}"
        else:
            result = "你没有选择任何兴趣"
        self.interest_result.config(text=result)

if __name__ == "__main__":
    root = tk.Tk()
    app = CheckbuttonComprehensive(root)
    root.mainloop()

实际应用示例

示例2:设置对话框

import tkinter as tk
from tkinter import messagebox

class SettingsDialog:
    def __init__(self, root):
        self.root = root
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        self.root.title("应用程序设置")
        self.root.geometry("500x450")
        self.root.resizable(False, False)
        
        # 创建主Frame
        main_frame = tk.Frame(self.root, padx=20, pady=20, bg="#f5f5f5")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(main_frame, text="应用程序设置", 
                              font=("Arial", 16, "bold"), bg="#f5f5f5")
        title_label.pack(pady=(0, 20))
        
        # 常规设置
        self.create_general_settings(main_frame)
        
        # 隐私设置
        self.create_privacy_settings(main_frame)
        
        # 通知设置
        self.create_notification_settings(main_frame)
        
        # 按钮区域
        self.create_buttons(main_frame)
        
    def create_general_settings(self, parent):
        """创建常规设置"""
        frame = tk.LabelFrame(parent, text="常规设置", padx=15, pady=15, 
                             font=("Arial", 10, "bold"), bg="white")
        frame.pack(fill=tk.X, pady=10)
        
        # 开机启动
        self.auto_start = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="开机自动启动", variable=self.auto_start, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 显示启动画面
        self.show_splash = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="显示启动画面", variable=self.show_splash, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 最小化到系统托盘
        self.minimize_to_tray = tk.BooleanVar()
        tk.Checkbutton(frame, text="最小化到系统托盘", variable=self.minimize_to_tray, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 自动检查更新
        self.auto_update = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="自动检查更新", variable=self.auto_update, 
                      bg="white").pack(anchor="w", pady=2)
        
    def create_privacy_settings(self, parent):
        """创建隐私设置"""
        frame = tk.LabelFrame(parent, text="隐私设置", padx=15, pady=15, 
                             font=("Arial", 10, "bold"), bg="white")
        frame.pack(fill=tk.X, pady=10)
        
        # 数据收集
        self.collect_usage_data = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="发送匿名使用数据", 
                      variable=self.collect_usage_data, bg="white").pack(anchor="w", pady=2)
        
        # 错误报告
        self.send_crash_reports = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="自动发送错误报告", 
                      variable=self.send_crash_reports, bg="white").pack(anchor="w", pady=2)
        
        # 个性化广告
        self.personalized_ads = tk.BooleanVar()
        tk.Checkbutton(frame, text="显示个性化广告", 
                      variable=self.personalized_ads, bg="white").pack(anchor="w", pady=2)
        
        # 保存搜索历史
        self.save_search_history = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="保存搜索历史", 
                      variable=self.save_search_history, bg="white").pack(anchor="w", pady=2)
        
    def create_notification_settings(self, parent):
        """创建通知设置"""
        frame = tk.LabelFrame(parent, text="通知设置", padx=15, pady=15, 
                             font=("Arial", 10, "bold"), bg="white")
        frame.pack(fill=tk.X, pady=10)
        
        # 邮件通知
        self.email_notifications = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="邮件通知", variable=self.email_notifications, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 推送通知
        self.push_notifications = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="推送通知", variable=self.push_notifications, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 声音提醒
        self.sound_alerts = tk.BooleanVar()
        tk.Checkbutton(frame, text="声音提醒", variable=self.sound_alerts, 
                      bg="white").pack(anchor="w", pady=2)
        
        # 桌面通知
        self.desktop_notifications = tk.BooleanVar(value=True)
        tk.Checkbutton(frame, text="桌面通知", variable=self.desktop_notifications, 
                      bg="white").pack(anchor="w", pady=2)
        
    def create_buttons(self, parent):
        """创建按钮区域"""
        button_frame = tk.Frame(parent, bg="#f5f5f5")
        button_frame.pack(fill=tk.X, pady=20)
        
        # 保存按钮
        save_btn = tk.Button(button_frame, text="保存设置", bg="#4CAF50", 
                           fg="white", font=("Arial", 10), padx=20,
                           command=self.save_settings)
        save_btn.pack(side=tk.RIGHT, padx=5)
        
        # 重置按钮
        reset_btn = tk.Button(button_frame, text="重置默认", bg="#f44336", 
                            fg="white", font=("Arial", 10), padx=20,
                            command=self.reset_settings)
        reset_btn.pack(side=tk.RIGHT, padx=5)
        
        # 取消按钮
        cancel_btn = tk.Button(button_frame, text="取消", bg="#9E9E9E", 
                             fg="white", font=("Arial", 10), padx=20,
                             command=self.root.destroy)
        cancel_btn.pack(side=tk.RIGHT, padx=5)
        
    def save_settings(self):
        """保存设置"""
        settings = {
            "auto_start": self.auto_start.get(),
            "show_splash": self.show_splash.get(),
            "minimize_to_tray": self.minimize_to_tray.get(),
            "auto_update": self.auto_update.get(),
            "collect_usage_data": self.collect_usage_data.get(),
            "send_crash_reports": self.send_crash_reports.get(),
            "personalized_ads": self.personalized_ads.get(),
            "save_search_history": self.save_search_history.get(),
            "email_notifications": self.email_notifications.get(),
            "push_notifications": self.push_notifications.get(),
            "sound_alerts": self.sound_alerts.get(),
            "desktop_notifications": self.desktop_notifications.get()
        }
        
        # 在实际应用中,这里会将设置保存到配置文件或数据库
        print("保存的设置:", settings)
        messagebox.showinfo("成功", "设置已保存!")
        
    def reset_settings(self):
        """重置为默认设置"""
        self.auto_start.set(True)
        self.show_splash.set(True)
        self.minimize_to_tray.set(False)
        self.auto_update.set(True)
        self.collect_usage_data.set(True)
        self.send_crash_reports.set(True)
        self.personalized_ads.set(False)
        self.save_search_history.set(True)
        self.email_notifications.set(True)
        self.push_notifications.set(True)
        self.sound_alerts.set(False)
        self.desktop_notifications.set(True)
        
        messagebox.showinfo("重置", "设置已重置为默认值!")

if __name__ == "__main__":
    root = tk.Tk()
    app = SettingsDialog(root)
    root.mainloop()

示例3:动态问卷调查

import tkinter as tk
from tkinter import messagebox
import json

class DynamicSurvey:
    def __init__(self, root):
        self.root = root
        self.current_question = 0
        self.answers = {}
        self.questions = self.load_questions()
        self.setup_ui()
        
    def load_questions(self):
        """加载问题数据"""
        questions = [
            {
                "id": 1,
                "text": "你使用哪些编程语言?",
                "type": "multiple",
                "options": ["Python", "JavaScript", "Java", "C++", "Go", "Rust", "其他"]
            },
            {
                "id": 2,
                "text": "你使用哪些开发工具?",
                "type": "multiple",
                "options": ["VS Code", "PyCharm", "IntelliJ", "Vim", "Sublime Text", "其他编辑器"]
            },
            {
                "id": 3,
                "text": "你参与过哪些类型的项目?",
                "type": "multiple",
                "options": ["Web开发", "数据分析", "机器学习", "移动开发", "桌面应用", "游戏开发"]
            },
            {
                "id": 4,
                "text": "你使用哪些操作系统?",
                "type": "multiple",
                "options": ["Windows", "macOS", "Linux", "其他"]
            }
        ]
        return questions
        
    def setup_ui(self):
        """设置用户界面"""
        self.root.title("动态问卷调查")
        self.root.geometry("600x500")
        self.root.configure(bg="#f0f8ff")
        
        # 标题
        title_frame = tk.Frame(self.root, bg="#f0f8ff")
        title_frame.pack(pady=20)
        
        self.title_label = tk.Label(title_frame, text="开发者问卷调查", 
                                   font=("Arial", 18, "bold"), bg="#f0f8ff")
        self.title_label.pack()
        
        self.progress_label = tk.Label(title_frame, text="", 
                                      font=("Arial", 10), bg="#f0f8ff", fg="#666")
        self.progress_label.pack()
        
        # 问题显示区域
        self.question_frame = tk.Frame(self.root, bg="white", relief=tk.GROOVE, bd=1)
        self.question_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 按钮区域
        self.button_frame = tk.Frame(self.root, bg="#f0f8ff")
        self.button_frame.pack(fill=tk.X, padx=20, pady=10)
        
        # 初始化显示第一个问题
        self.show_question()
        
    def show_question(self):
        """显示当前问题"""
        # 清除之前的问题
        for widget in self.question_frame.winfo_children():
            widget.destroy()
            
        # 清除按钮
        for widget in self.button_frame.winfo_children():
            widget.destroy()
            
        if self.current_question >= len(self.questions):
            self.show_results()
            return
            
        question = self.questions[self.current_question]
        
        # 更新进度
        self.progress_label.config(
            text=f"问题 {self.current_question + 1}/{len(self.questions)}"
        )
        
        # 显示问题文本
        question_label = tk.Label(self.question_frame, text=question["text"], 
                                 font=("Arial", 12, "bold"), bg="white", 
                                 wraplength=500, justify="left")
        question_label.pack(anchor="w", pady=20, padx=20)
        
        # 创建复选框
        self.current_vars = []
        for option in question["options"]:
            var = tk.BooleanVar()
            self.current_vars.append((option, var))
            
            check = tk.Checkbutton(self.question_frame, text=option, 
                                  variable=var, bg="white", font=("Arial", 10),
                                  anchor="w", justify="left")
            check.pack(anchor="w", pady=5, padx=40, fill=tk.X)
            
        # 创建导航按钮
        if self.current_question > 0:
            prev_btn = tk.Button(self.button_frame, text="上一题", 
                               bg="#2196F3", fg="white", font=("Arial", 10),
                               command=self.previous_question)
            prev_btn.pack(side=tk.LEFT, padx=5)
            
        if self.current_question < len(self.questions) - 1:
            next_btn = tk.Button(self.button_frame, text="下一题", 
                               bg="#4CAF50", fg="white", font=("Arial", 10),
                               command=self.next_question)
            next_btn.pack(side=tk.RIGHT, padx=5)
        else:
            submit_btn = tk.Button(self.button_frame, text="提交问卷", 
                                 bg="#FF9800", fg="white", font=("Arial", 10),
                                 command=self.next_question)
            submit_btn.pack(side=tk.RIGHT, padx=5)
            
        # 跳过按钮
        skip_btn = tk.Button(self.button_frame, text="跳过", 
                           bg="#9E9E9E", fg="white", font=("Arial", 10),
                           command=self.next_question)
        skip_btn.pack(side=tk.RIGHT, padx=5)
        
    def next_question(self):
        """转到下一题"""
        self.save_current_answers()
        self.current_question += 1
        self.show_question()
        
    def previous_question(self):
        """转到上一题"""
        self.save_current_answers()
        self.current_question -= 1
        self.show_question()
        
    def save_current_answers(self):
        """保存当前问题的答案"""
        if self.current_question < len(self.questions):
            question = self.questions[self.current_question]
            selected_options = [option for option, var in self.current_vars if var.get()]
            self.answers[question["id"]] = {
                "question": question["text"],
                "answer": selected_options
            }
            
    def show_results(self):
        """显示调查结果"""
        # 清除界面
        for widget in self.question_frame.winfo_children():
            widget.destroy()
            
        for widget in self.button_frame.winfo_children():
            widget.destroy()
            
        self.title_label.config(text="调查完成!")
        self.progress_label.config(text="感谢您的参与")
        
        # 显示结果
        result_text = tk.Text(self.question_frame, wrap=tk.WORD, font=("Arial", 10),
                             bg="white", padx=20, pady=20)
        result_text.pack(fill=tk.BOTH, expand=True)
        
        result_text.insert(tk.END, "你的回答总结:\n\n")
        
        for qid, answer_data in self.answers.items():
            result_text.insert(tk.END, f"{answer_data['question']}\n")
            if answer_data["answer"]:
                result_text.insert(tk.END, f"  选择: {', '.join(answer_data['answer'])}\n")
            else:
                result_text.insert(tk.END, "  未选择任何选项\n")
            result_text.insert(tk.END, "\n")
            
        result_text.config(state=tk.DISABLED)
        
        # 添加滚动条
        scrollbar = tk.Scrollbar(self.question_frame, command=result_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        result_text.config(yscrollcommand=scrollbar.set)
        
        # 重新开始按钮
        restart_btn = tk.Button(self.button_frame, text="重新开始", 
                              bg="#4CAF50", fg="white", font=("Arial", 10),
                              command=self.restart_survey)
        restart_btn.pack(side=tk.RIGHT, padx=5)
        
        # 导出按钮
        export_btn = tk.Button(self.button_frame, text="导出结果", 
                             bg="#2196F3", fg="white", font=("Arial", 10),
                             command=self.export_results)
        export_btn.pack(side=tk.RIGHT, padx=5)
        
    def restart_survey(self):
        """重新开始调查"""
        self.current_question = 0
        self.answers = {}
        self.title_label.config(text="开发者问卷调查")
        self.show_question()
        
    def export_results(self):
        """导出结果"""
        try:
            with open("survey_results.json", "w", encoding="utf-8") as f:
                json.dump(self.answers, f, ensure_ascii=False, indent=2)
            messagebox.showinfo("导出成功", "结果已导出到 survey_results.json")
        except Exception as e:
            messagebox.showerror("导出失败", f"导出时发生错误: {str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = DynamicSurvey(root)
    root.mainloop()

Checkbutton的主要方法和属性

# 创建Checkbutton
checkbutton = tk.Checkbutton(parent, **options)

# 主要配置选项
checkbutton.config(
    text="选项文本",          # 显示的文本
    variable=var,            # 关联的变量 (BooleanVar, IntVar, StringVar)
    onvalue=1,               # 选中时的值 (StringVar/IntVar使用)
    offvalue=0,              # 未选中时的值 (StringVar/IntVar使用)
    command=callback,        # 状态改变时的回调函数
    state="normal",          # 状态: normal, disabled, active
    bg="white",              # 背景色
    fg="black",              # 前景色
    selectcolor="color",     # 选中时的背景色
    font=("Arial", 10),      # 字体
    padx=10,                 # 水平内边距
    pady=5,                  # 垂直内边距
    anchor="w",              # 文本对齐
    justify="left",          # 多行文本对齐
    indicatoron=True,        # 是否显示指示器
    wraplength=200           # 文本换行长度
)

# 主要方法
checkbutton.select()         # 选中复选框
checkbutton.deselect()       # 取消选中
checkbutton.toggle()         # 切换状态
checkbutton.invoke()         # 调用关联的命令
checkbutton.flash()          # 闪烁显示

# 状态检查
checkbutton.cget("text")     # 获取配置值
var.get()                    # 获取选中状态

# 事件绑定
checkbutton.bind("<Button-1>", callback)  # 鼠标点击事件

使用场景总结

  1. 设置对话框:应用程序的各种开关设置
  2. 问卷调查:多选问题的答案收集
  3. 过滤器:数据筛选和条件选择
  4. 功能开关:启用或禁用特定功能
  5. 偏好设置:用户个性化偏好配置
  6. 批量操作:选择多个项目进行批量处理
  7. 权限管理:角色和权限的多选配置

Checkbutton是创建用户交互界面的重要组件,特别适合需要多选操作的场景。通过合理使用Checkbutton,可以创建出功能丰富、用户友好的应用程序界面。

举报
0 条评论