首页 > 解决方案 > 如何计算按钮的点击次数

问题描述

如何计算我程序中 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

标签: pythontkinter

解决方案


我不知道这个脚本是否是覆盖文件中数字的最佳脚本,但您可以尝试一下。如果您的文件是空的,它将创建行(例如:)dog = 0,如果存在,它将dog = 1在您单击按钮时增加它(例如:)。

我还删除了您的from Tkinter import *,而是将所有小部件替换Buttontk.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

推荐阅读