【问题标题】:How to count the number of clicks for button如何计算按钮的点击次数
【发布时间】:2020-05-30 07:11:34
【问题描述】:

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

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    我不知道这个脚本是否是覆盖文件中数字的最佳脚本,但你可以试试。如果您的文件为空,它将创建行(例如: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
    

    【讨论】:

    • 非常感谢亲爱的要求和你的代码一样。但是我不明白你在 def save_in_file(animal) 中做了什么:如果可能的话,你能逐行解释吗?
    • 我用 cmets 更新了我的答案,如果还不清楚,请告诉我
    【解决方案2】:
    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)
    

    【讨论】:

    • 嗨,我遇到以下错误,请澄清 Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):文件“C:\Users\naman\AppData\Local\Programs\Python\Python38-32 \lib\tkinter_init_.py",第 1883 行,在 call 中返回 self.func(*args) 文件“C:/Users/naman/OneDrive/Desktop/tst or.py",第 13 行,在 cat 中,内容为 open("log.txt").read():AttributeError: enter
    • 在开始之前,您需要在不同的行上创建一个包含两个零的 log.txt 文件
    • with open("log.txt").read() as contents: 将引发异常,因为str 不支持context manager 功能。
    【解决方案3】:

    您也可以只创建一个命令,每次单击都会将一个变量添加到变量中。

    【讨论】:

    • 你的答案很短,你应该在开始投反对票之前解释一下。
    • 请详细说明
    • 当然,你需要你的按钮来做一些点击所以你给它一个命令检查这个[链接]stackoverflow.com/questions/6874525/…,看看他们是怎么做的按钮
    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多