首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有tkinter的简易秒表程序

带有tkinter的简易秒表程序
EN

Code Review用户
提问于 2020-05-26 14:54:20
回答 1查看 281关注 0票数 4

我自学了Python,最近开始学习tkinter。我做了一个简单的秒表程序,我想知道代码是否干净,是否以代码高效的方式编写。我将非常感谢任何关于如何改进我的代码的建议!谢谢!

代码语言:javascript
复制
from tkinter import *
import time

root = Tk()

numberOfSeconds = 0

def counting():
    global numberOfSeconds
    global stopCounting

    if stopCounting == False:
        numberOfSeconds += 1
        seconds.config(text=str(numberOfSeconds))
        seconds.after(1000, counting)
    elif stopCounting == True:
        stopCounting = False
        numberOfSeconds = 0
        seconds.config(text=str(numberOfSeconds))


def start():
    global stopCounting
    stopCounting = False
    stopButton.config(state=NORMAL)
    seconds.after(1000, counting)

def stop():
    global stopCounting
    stopButton.config(state=DISABLED)
    stopCounting = True


seconds = Label(text=str(numberOfSeconds))
startButton = Button(text="Start", command=start)
stopButton = Button(text="Stop", command=stop, state=DISABLED)

seconds.grid(row=0, column=0, columnspan=2)
startButton.grid(row=1, column=0)
stopButton.grid(row=1, column=1)

root.mainloop()
EN

回答 1

Code Review用户

回答已采纳

发布于 2020-05-26 15:16:50

Globals

一般来说,用这样的球体不是个好主意。它伤害了重新进入。如果您希望同时支持两个秒表,无论是在一个UI中还是作为一个web服务器,该怎么办?有这样的球体会防止这种情况发生。

这也损害了可测试性。测试依赖于全局状态的方法要比测试那些在对象上下文(self)或作为方法参数中传递状态的自包含方法更困难。

解决这个问题的一种方法是创建一个具有属性number_of_secondsis_counting的类(我发现这比stop_counting更直观)。

Booleans

这个街区:

代码语言:javascript
复制
if stopCounting == False:
    numberOfSeconds += 1
    seconds.config(text=str(numberOfSeconds))
    seconds.after(1000, counting)
elif stopCounting == True:
    stopCounting = False
    numberOfSeconds = 0
    seconds.config(text=str(numberOfSeconds))

更容易表达为

代码语言:javascript
复制
if stopCounting:
    stopCounting = False
    numberOfSeconds = 0
    seconds.config(text=str(numberOfSeconds))
else:
    numberOfSeconds += 1
    seconds.config(text=str(numberOfSeconds))
    seconds.after(1000, counting)

变量名

它们应该是lower_snake_case,即start_button

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/242956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档