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