python - 如何计算按钮的点击次数
问题描述
如何计算我程序中 CAT 或 DOG 按钮的点击次数并保存到 log.txt
from Tkinter import *
import Tkinter as tk
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)
Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()
sys.stdout.close()
sys.stdout=stdoutOrigin
解决方案
我不知道这个脚本是否是覆盖文件中数字的最佳脚本,但您可以尝试一下。如果您的文件是空的,它将创建行(例如:)dog = 0
,如果存在,它将dog = 1
在您单击按钮时增加它(例如:)。
我还删除了您的from Tkinter import *
,而是将所有小部件替换Button
为tk.Button
。
def save_in_file(animal):
f = open("log.txt", "r+")
animal_exists = False
data = f.read()
# separate the file into lines
lines = data.split("\n") # list of lines : ['dog = 2', 'cat = 1']
for i, v in enumerate(lines):
# separate the lines into words
words = v.split() # list of words : ['dog', '=', '3']
if animal in words:
animal_exists = True
# here we search for the "number_to_increment"
number_to_increment = words[-1]
# we convert "number_to_increment" into integer, then add 1
new_number = str(int(number_to_increment) +1)
# we convert "new_number" back to string
words[-1] = new_number
# concatenate words to form the new line
lines[i] = " ".join(words)
# creates a new line with "animal = 0" if "animal" is not in file
if not animal_exists:
if lines[0] == "":
lines.remove("")
lines.append("{} = 0".format(animal))
# concatenate all lines to get the whole text for new file
data = "\n".join(lines)
f.close()
# open file with write permission
f = open("log.txt", "wt")
# overwrite the file with our modified data
f.write(data)
f.close()
def cat():
save_in_file("cat")
def dog():
save_in_file("dog")
import tkinter as tk
master = tk.Tk()
tk.Label(master, text='Who is your favourate animal ?? ').grid(row=0)
tk.Button(master, text='CAT', command=cat).grid(row=1, sticky="w", pady=4)
tk.Button(master, text='DOG', command=dog).grid(row=1,column=1,sticky="w", pady=4)
master.mainloop()
输出 :
# log.txt
dog = 2
cat = 1
推荐阅读
- javascript - document.addEventListener("touchmove") 与 document.ontouchmove
- php - 用 PHP 发送邮件收到一些不需要的值
- javascript - 在java脚本前端生成可下载的二维码
- sql-server - 无法连接到 MSSQL 服务器
- javascript - Sent value is seen as reference instead of value javascript
- ext4 - 为什么要在 umountfs 脚本中卸载之前将文件系统重新挂载为只读?
- excel - 在多个单元格中查找重复数据并将所有数据复制到其他 Excel 工作表
- abap - SAP NetWeaver RFC SDK 文档?
- javascript - mb_convert_encoding 有时不起作用:未捕获的 URIError:URI 格式错误
- vba - Outlook vba - 如何在转发、回复或重播给所有人之前在邮件主题上添加后缀?