Tkinter,xlwt,尝试编辑已在循环中创建的复选按钮

时间:2019-12-14 15:15:00

标签: python tkinter

这是我在tkinter中的寄存器代码的一部分,该寄存器也使用xlwt,xlutils和xlrd(Excel模块)。它从文件中获取名称,并在这些名称旁边创建带有“当前”复选按钮的名称列表:

https://imgur.com/a/hTrhWFy

我想保存检查按钮的打开和关闭值,以便可以将它们放在excel电子表格中,但是因为我已经在循环中创建了它们,所以变量对于所有它们都是相同的,因此如果我添加它并单击它们,它们都将打开和关闭。

有人知道如何解决此问题吗?

    x=0
    y=1
    for line in open(register,"r"):
        with open(register,"r") as file:
            all_lines=file.readlines()
        Label(registersuccess,text=all_lines[x].strip("\n")).grid(column=0,row=x)
        Checkbutton(registersuccess,text="Present").grid(column=1,row=x)
        listeesheet.write(x,0,all_lines[x].strip("\n"))

        entrysheet.write(y,0,all_lines[x].strip("\n"))
        entrywb.save(filename)
        x=x+1
        y=y+1

1 个答案:

答案 0 :(得分:2)

如果要在循环外保存一个checkbutton的值,则看起来像这样:

present = tk.IntVar()
tk.Checkbutton(root, text="Present", variable=present)

这将创建一个新的Tkinter Variable,当按下复选按钮时,它等于1,而当未选中它时,它等于0(可以使用参数offvalue和{ {1}}。

如果要在循环中执行相同的操作,则将所有checkbutton变量放入字典中,如下所示:

onvalue

可以通过使用列表import tkinter as tk # recommended over the use of "from tkinter import *" root = tk.Tk() def get_present(): for name, present in register_dict.items(): # searches through the dictionary, and puts the persons name into the variable name and the checkbutton variable into the present variable print(name, present.get()) # present.get() gets the current value of a tkinter variable register = "names.txt" # Use your own text file with open(register,"r") as file: # moved outside of the loop to prevent the system reloading the file every time - saves time all_lines=file.readlines() registersuccess = tk.Frame(root) # Use your own registersuccess Frame/Window registersuccess.grid(row=0, column=0) x=0 y=1 register_dict = {} # creates an empty dictionary for line in open(register,"r"): # for each line in the register name = all_lines[x].strip("\n") # get the current name and remove the enter key tk.Label(registersuccess,text=name).grid(column=0,row=x) # Add a label with the name register_dict[name] = tk.IntVar() # places into the register dictionary the key: name, and a new integer tk.Checkbutton(registersuccess,text="Present", variable=register_dict[name]).grid(column=1,row=x) # on a checkbutton change the variable will be updated accordingly x += 1 # A more python way to write x = x + 1 y += 1 tk.Button(registersuccess, command=get_present, text="Print Present").grid(column=0, row=x, rowspan=2) # Prints the values (can be removed for your project) root.mainloop() 而不是重新打开文件来进一步优化此代码:

all lines

此后机器上的计时如下:

for line in all_lines:
    name = line.strip("\n")

要查看的导入数字是用户看到效果所需的时间长度和$ python3 optimized.py real 0m0.312s user 0m0.073s sys 0m0.013s $ python3 unoptimized.py real 0m0.318s user 0m0.059s sys 0m0.030s 的数量(优化的代码快将近3倍)