提问者:小点点

_tkinter.tclerror:错误的窗口路径名“。!checkbutton”


我正在尝试创建一个应用程序,从一个复选框列表中找到某些字段。 我在调用search函数时被困在self.text.window_create("end“,window=cb)。 虽然在运行__init_中的行时运行良好,但在这里会抛出一个错误。

import tkinter as tk

class App:

    def search(self):
        searched_field = self.search_box.get()
        found_indexes = []

        for i in range(len(self.name_list)):
            if searched_field in self.name_list[i]:
                found_indexes.append(i)

        self.text.delete("1.0", "end")

        for i in range(len(found_indexes)):
            cb = self.check_buttons[found_indexes[i]]
            self.text.window_create("end", window=cb)
            self.text.insert("end", "\n")

    def write_names(self):

        name_file = "names.txt"

        with open(name_file, "w") as file:

            for name in self.returned_list:
                file.write(name + "\n")

    def __init__(self, root, name_list):

        self.check_buttons = []
        self.var_list = []
        self.returned_list = []

        self.name_list = name_list
        self.start = 0

        self.search_box = tk.Entry(root)
        self.search_box.pack(side="top")
        self.search_button = tk.Button(root, text='Search', command=self.search)
        self.search_button.pack()

        self.scroll_bar = tk.Scrollbar(orient="vertical")
        self.text = tk.Text(root, width=20, height=10, yscrollcommand=self.scroll_bar.set)
        self.scroll_bar.config(command=self.text.yview)
        self.scroll_bar.pack(side="right", anchor="ne", fill="y")
        self.text.pack(side="top", fill="both", expand=True)

        for name in name_list:
            var = tk.BooleanVar()
            cb = tk.Checkbutton(text=name, padx=0, pady=0, bd=0, variable=var)
            self.check_buttons.append(cb)
            self.var_list.append(var)

        for cb in self.check_buttons:
            self.text.window_create("end", window=cb)
            self.text.insert("end", "\n")

        tk.Button(root, text='Write names', command=self.write_names()).pack()
        tk.Button(root, text='Quit', command=root.quit).pack()

name_list = ["aaa", "bbbb", "cccc", "abcd"]
root = tk.Tk()
app = App(root, name_list)
root.mainloop()

共1个答案

匿名用户

您需要传入tkinter根

cb = tk.Checkbutton(root, text=name, padx=0, pady=0, bd=0, variable=var)

与其他按钮类似

self.search_button = tk.Button(root, text='Search', command=self.search)