如何计算按钮的点击次数



如何计算程序中 CAT 或 DOG 按钮的点击次数并保存到日志中.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 *,取而代之的是,我为所有小部件用tk.Button替换了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
cats = 0
dogs = 0
def cat():
with open("log.txt").read() as contents:
file = open("log.txt", "w")
file.write(str(int(contents.split()[0]) + 1) + "n" + contents.split()[1])
file.close()
def dog():
with open("log.txt").read() as contents:
file = open("log.txt", "w")
file.write(contents.split()[0] + "n" + str(int(contents.split()[1]) + 1))
file.close()
Button(master, text='CAT' , command=cat).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' , command=dog).grid(row=1,column=1,sticky=W, pady=4)

您也可以制作一个命令,每次单击都会向变量添加一个命令。

最新更新