我正试着做一个小小的电梯推介节目来展示我自己.程序从2分钟开始倒计时,我希望它每20秒自动更新一张图片.这让我可以在20秒内详细介绍所显示的图片,然后继续.
然而,我被困在了图像切换部分.我已经研究了.After()、.time()、.sleep(),并研究了线程--这对我来说仍然是一个未知且粗糙的概念.
到目前为止,这就是我所在的地方.
目前,我的 idea 到处都是,我不确定哪种方法(最好)可行.我考虑过在倒计时函数中使用嵌套的if语句,但我认为这会使一切变得非常难以阅读.
我已经考虑过设置第二个函数来处理图像更改,您可以在下面看到一个早期的不起作用的示例.
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
import math
import time
import datetime
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
BLUE = "#678ac2"
FONT_NAME = "Courier"
REPEATS = 0
# ---------------------------- TIMER MECHANISM ------------------------------- #
def countdown(total_seconds=60, total_minutes=2):
if total_seconds == 60:
total_seconds -= 1
total_minutes -= 1
timer_text.config(text=f"{total_minutes}:{total_seconds}")
window.after(1000, countdown, total_seconds, total_minutes)
elif total_seconds == 1 and total_minutes != 0:
total_seconds += 59
timer_text.config(text=f"{total_minutes}:00")
window.after(1000, countdown, total_seconds, total_minutes)
elif total_seconds == 0 and total_minutes > 0:
total_seconds = 59
total_minutes -= 1
timer_text.config(text=f"{total_minutes}:{total_seconds}")
window.after(1000, countdown, total_seconds, total_minutes)
elif 11 > total_seconds > 0:
total_seconds -= 1
timer_text.config(text=f"{total_minutes}:0{total_seconds}")
window.after(1000, countdown, total_seconds, total_minutes)
elif total_seconds == 0 and total_minutes == 0:
pass
else:
total_seconds -= 1
timer_text.config(text=f"{total_minutes}:{total_seconds}")
window.after(1000, countdown, total_seconds, total_minutes)
def image_change():
global REPEATS
REPEATS += 1
if REPEATS == 1:
second_img = (Image.open("edward.png"))
second_resized_image = second_img.resize((850, 450), Image.LANCZOS)
second_new_image = ImageTk.PhotoImage(second_resized_image)
canvas.create_image(450, 225, anchor=CENTER, image=second_new_image)
elif REPEATS == 2:
print("repeats worked once")
else:
print("Error with repeats")
# ---------------------------- UI SETUP ------------------------------- #
# Create window & canvas
window = Tk()
window.title("Elevator Pitch")
window.geometry("900x600")
window.configure(bg=BLUE)
canvas = Canvas(window, width=900, height=500, bg=BLUE)
canvas.grid(column=1, row=1)
img = (Image.open("paco.png"))
resized_image = img.resize((850, 450), Image.LANCZOS)
new_image = ImageTk.PhotoImage(resized_image)
canvas.create_image(450, 225, anchor=CENTER, image=new_image)
# Create timer text & button
timer_text = Label(window, text="2:00", font=(FONT_NAME, 35, "bold"), bg=BLUE)
timer_text.grid(column=1, row=2)
start_button = Button(text="Start", command=countdown)
start_button.grid(column=1, row=3)
# Create new images
window.mainloop()