首页 > 解决方案 > 如何计算按钮点击?

问题描述

我想数数并写入 csv 文件。在第一列我想写按钮计数,在另一个按钮上我想写文本。我创建了一个用 csv 编写的函数。我将 tkinter 用于 GUI

def functie2(l, m):
    with open('employee_file3.csv', 'a+', newline = "\n") as csv_file:
     
        global click
        click += 1
        print(click)


        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                
        writer.writerow({'Nr_crt': l, 'Prelucrare': m})

class Pag4(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Alege prelucrarea")
        label.pack(pady=10,padx=10)
        self.controller = controller
        label = tk.Label(self, text="Pagina 4")
        button = tk.Button(self, text="Srunjire", command=lambda: [functie2('l', 'Strunjire'), controller.show_frame("Pag20")])
      
        button.pack()

标签: pythontkinterbuttoncountclick

解决方案


您需要click在全局范围内进行初始化。如果您希望 CSV 文件中的第一列是点击次数,您应该替换lclick并且不需要传递lfunctie2()

click = 0   # initialize click

def functie2(m):
    global click
    with open('employee_file3.csv', 'a+', newline="\n") as csv_file:
        click += 1
        print(click)

        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writerow({'Nr_crt': click, 'Prelucrare': m})

class Pag4(tk.Frame):
    def __init__(self, parent, controller):
        ...
        button = tk.Button(self, text="Srunjire", command=lambda: [functie2('Strunjire'), controller.show_frame("Pag20")])
        button.pack()

我建议functie2()进入Pag4课堂,以便您可以使用实例变量而不是全局变量:

class Pag4(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Alege prelucrarea")
        label.pack(pady=10, padx=10)
        self.controller = controller
        self.click = 0
        label = tk.Label(self, text="Pagina 4")
        button = tk.Button(self, text="Srunjire", command=lambda: [self.functie2('Strunjire'), controller.show_frame("Pag20")])
        button.pack()

    def functie2(self, m):
        self.click += 1
        print(self.click)

        with open('employee_file3.csv', 'a+', newline="\n") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writerow({'Nr_crt': self.click, 'Prelucrare': m})

推荐阅读