python - 如何计算按钮点击?
问题描述
我想数数并写入 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()
解决方案
您需要click
在全局范围内进行初始化。如果您希望 CSV 文件中的第一列是点击次数,您应该替换l
为click
并且不需要传递l
给functie2()
:
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})
推荐阅读
- javascript - 如何使其余代码在 fun1 中等待直到 fun2() 完成,其中 fun2 是 fun1 中的嵌套函数?
- redis - key过期时触发操作[redis]
- c++ - C++ 应用程序在创建 std::thread 时立即在 clone.S 中的某处崩溃
- windows - 直接在 CMD 上运行 PowerShell 命令会导致索引超出范围错误
- css - css-in-js & react-icons:如何将 svg 图标传递给 css 剪辑路径属性?
- azure - 使用 Azure Cloud Shell 部署 ps1 脚本时出现“一元运算符预期”错误
- javascript - 如何在 Jquery 中将多选重置为其第一个值
- node.js - 获取实时重新编码视频的内容长度
- pyspark - pyspark 读取制表符分隔符未按预期运行
- javascript - 复制和粘贴交叉表 Chrome 扩展