用python canvas和tkinter交互制作一个电子表,实现显示时间与倒计时两种模式,附上代码
时间: 2024-03-07 13:49:42 浏览: 29
好的,我可以为您提供相关的代码。以下是一个简单的电子表程序,可以在Python中使用canvas和tkinter交互实现。
```python
import tkinter as tk
import time
class DigitalClock:
def __init__(self, master):
self.master = master
self.mode = 'time'
self.time_format = '%H:%M:%S'
self.countdown_time = 60
self.canvas = tk.Canvas(master, width=200, height=100)
self.canvas.pack()
self.draw_clock()
def draw_clock(self):
self.canvas.delete('all')
if self.mode == 'time':
current_time = time.strftime(self.time_format)
self.canvas.create_text(100, 50, text=current_time, font=('Helvetica', 30), tags='time')
elif self.mode == 'countdown':
self.canvas.create_text(100, 50, text=self.countdown_time, font=('Helvetica', 30), tags='countdown')
def switch_mode(self):
if self.mode == 'time':
self.mode = 'countdown'
else:
self.mode = 'time'
self.draw_clock()
def start_countdown(self):
self.mode = 'countdown'
self.countdown_time = 60
self.do_countdown()
def do_countdown(self):
if self.countdown_time > 0:
self.canvas.delete('countdown')
self.canvas.create_text(100, 50, text=self.countdown_time, font=('Helvetica', 30), tags='countdown')
self.countdown_time -= 1
self.master.after(1000, self.do_countdown)
else:
self.switch_mode()
root = tk.Tk()
clock = DigitalClock(root)
button = tk.Button(root, text='Switch Mode', command=clock.switch_mode)
button.pack()
button2 = tk.Button(root, text='Start Countdown', command=clock.start_countdown)
button2.pack()
root.mainloop()
```
在此代码中,我们创建了一个名为DigitalClock的类,该类包括了一个画布对象,用于在屏幕上显示时间或倒计时。我们还创建了两个按钮,一个用于切换模式,另一个用于启动倒计时。当切换模式时,我们会在时间模式和倒计时模式之间切换。在倒计时模式下,我们使用递归调用和after方法来实现倒计时的效果。
希望这可以帮助到您!