我自学了Python,最近开始学习tkinter。我做了一个简单的秒表程序,我想知道代码是否干净,是否以代码高效的方式编写。我将非常感谢任何关于如何改进我的代码的建议!谢谢!
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()发布于 2020-05-26 15:16:50
一般来说,用这样的球体不是个好主意。它伤害了重新进入。如果您希望同时支持两个秒表,无论是在一个UI中还是作为一个web服务器,该怎么办?有这样的球体会防止这种情况发生。
这也损害了可测试性。测试依赖于全局状态的方法要比测试那些在对象上下文(self)或作为方法参数中传递状态的自包含方法更困难。
解决这个问题的一种方法是创建一个具有属性number_of_seconds和is_counting的类(我发现这比stop_counting更直观)。
这个街区:
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))更容易表达为
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。
https://codereview.stackexchange.com/questions/242956
复制相似问题