Как посчитать количество нажатий на кнопку - PullRequest
0 голосов
/ 14 февраля 2020

Как посчитать количество нажатий на кнопку 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

Ответы [ 3 ]

2 голосов
/ 14 февраля 2020

Я не знаю, является ли этот скрипт лучшим для перезаписи числа в файле, но вы можете попробовать его. Если ваш файл пуст, он создаст строки (например, 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
1 голос
/ 14 февраля 2020

Вы также можете просто создать команду, которая добавляет один к переменной каждый клик.

1 голос
/ 14 февраля 2020
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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...