使用 tkinter 检查特定的复选框

Check a specific checkbox with tkinter

我的项目有几个复选框,我想将其中一些标记为已选中

[一个例子]

如何标记特定的?

我试过了

self.checkButton[2].select()

self.checkButton['checkbox_2'].select()

self.checkButton.select(2)

但没有成功,我该如何选中特定的复选框?

self.checkButton 是我的复选框

self.checkButton = tkinter.Checkbutton(self.canvas, background="white", ...)

就像@acw1668 和this website 建议的那样,尝试使用self.checkButton.select()self 是您对 window 及其所有小部件的称呼。 checkButton 是您的复选按钮的名称,如果您通过 c1 = tk.Checkbutton(window, text='Python', variable=var1) 调用复选按钮,那么您将使用 self.c1.select()select 是用于检查复选框的方法。希望这有点帮助。如果您对此答案有任何疑问,请发表评论,我会尽力提供帮助。

要恢复 Checkbutton 的值,您必须将它们关联到一些变量并使用它的 .set() .get() 方法。

如果您愿意,我已经用 Checkbutton 和 Radiobutton 写了一个完整的例子。

#!/usr/bin/python3
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox


class Main(ttk.Frame):
    def __init__(self, parent, ):
        super().__init__(name="main")

        self.parent = parent
        
        
        self.option = tk.IntVar()
        self.check_one = tk.BooleanVar()
        self.check_two = tk.BooleanVar()
        self.check_three = tk.BooleanVar()
        self.check_four = tk.BooleanVar()
        self.values = ('Apple','Banana','Orange')
       
        self.init_ui()
          
    def init_ui(self):

        f0 = ttk.Frame(self)
        f1 = ttk.Frame(f0,)

        ttk.Label(f1, text="First Checkbox:").pack()
        self.checkbox_1 = ttk.Checkbutton(f1, onvalue=1, offvalue=0, name = "first_checkbox", variable=self.check_one).pack()

        ttk.Label(f1, text="Second Checkbox:").pack()
        self.checkbox_2 = ttk.Checkbutton(f1, onvalue=1, offvalue=0, name = "second_checkbox", variable=self.check_two).pack()

        ttk.Label(f1, text="Third Checkbox:").pack()
        self.checkbox_3 = ttk.Checkbutton(f1, onvalue=1, offvalue=0, name = "third_checkbox", variable=self.check_three).pack()

        ttk.Label(f1, text="Fourth Checkbox:").pack()
        self.checkbox_4 = ttk.Checkbutton(f1, onvalue=1, offvalue=0, name = "fourth_checkbox", variable=self.check_four).pack()


        ttk.Label(f1, text="Radiobutton:").pack()
        for index, text in enumerate(self.values):
            ttk.Radiobutton(f1,
                            text=text,
                            variable=self.option,
                            value=index,).pack()
            

        f2 = ttk.Frame(f0,)

        bts = [("Callback", 7, self.on_callback, "<Alt-k>"),
               ("Close", 0, self.on_close, "<Alt-c>")]

        for btn in bts:
            ttk.Button(f2,
                       text=btn[0],
                       underline=btn[1],
                       command = btn[2]).pack(fill=tk.X, padx=5, pady=5)
            self.parent.bind(btn[3], btn[2])
            
        f1.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        f2.pack(side=tk.RIGHT, fill=tk.Y, expand=0)
        f0.pack(fill=tk.BOTH, expand=1)
        
    def on_callback(self, evt=None):
           
        print ("self.first_checkbox = {0}".format(self.check_one.get()))
        print ("self.second_checkbox = {0}".format(self.check_two.get()))
        print ("self.third_checkbox = {0}".format(self.check_three.get()))
        print ("self.fourth_checkbox = {0}".format(self.check_four.get()))

        print ("self.option = {}".format(self.option.get()))
        

    def on_close(self, evt=None):
        self.parent.on_exit()

class App(tk.Tk):
    """Main Application start here"""
    def __init__(self, *args, **kwargs):
        super().__init__()

        self.protocol("WM_DELETE_WINDOW", self.on_exit)
        self.set_style(kwargs["style"])  
        self.set_title(kwargs["title"])
        self.resizable(width=False, height=False)
        
        Main(self).pack(fill=tk.BOTH, expand=1)

    def set_style(self, which):
        self.style = ttk.Style()
        self.style.theme_use(which)
        
    def set_title(self, title):
        s = "{0}".format(title)
        self.title(s)
        
    def on_exit(self):
        """Close all"""
        msg = "Do you want to quit?"
        if messagebox.askokcancel(self.title(), msg, parent=self):
            self.destroy()

def main():

    args = []

    for i in sys.argv:
        args.append(i)

    #('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
    kwargs = {"style":"clam", "title":"Simple App",}

    app = App(*args, **kwargs)

    app.mainloop()

if __name__ == '__main__':
    main()