我正试着做一个小小的电梯推介节目来展示我自己.程序从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()


推荐答案

当倒计时可被20秒整除时,您可以更改图像.我简化了你的倒计时,所以它只用秒数来让这件事变得更容易.我已经添加了load_image函数来删除已有的图像,然后显示下一个图像.它使用popIMAGES数组中获取和删除第一个图像.

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"
# Changes start here
IMAGES = ["first.png", "second.png", "third.png", ...] # Put your image file paths here
CURRENT_IMAGE = None
CURRENT_PHOTOIMAGE = None

# ---------------------------- TIMER MECHANISM ------------------------------- #

def countdown(total_seconds=120):
    total_seconds -= 1
    minutes, seconds = divmod(total_seconds, 60)
    timer_text.config(text = f"{minutes}:{seconds:02d}")
    if total_seconds % 20 == 0 and IMAGES: # Will be called every 20 seconds if there are any images left
        load_image()
    if total_seconds > 0:
        window.after(1000, countdown, total_seconds)


def load_image():
    global CURRENT_IMAGE, CURRENT_PHOTOIMAGE
    if IMAGES:
        if CURRENT_IMAGE:
            canvas.delete(CURRENT_IMAGE)
        img = Image.open(IMAGES.pop(0))
        resized_image = img.resize((850, 450), Image.LANCZOS)
        # It's important to keep a reference to the PhotoImage or it'll get garbage collected
        CURRENT_PHOTOIMAGE = ImageTk.PhotoImage(resized_image)
        CURRENT_IMAGE = canvas.create_image(450, 225, anchor=CENTER, image=CURRENT_PHOTOIMAGE)


# ---------------------------- 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)

load_image()
# Changes end here
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()

Python-3.x相关问答推荐

在numpy. linalg的qr之后使用scipy. integrate中的solve_ivp时出现了一个奇怪的错误

这是重命名极地df列的最好方式吗?

PythonPandas -通过知道位置(Loc)而不是索引来删除行

TypeError:&Quot;Value&Quot;参数必须是标量、Dict或Series,但您传递了&Quot;Index&Quot;

估计列表中连续对的数量

错误:无法为 pyconcorde 构建轮子,这是安装基于 pyproject.toml 的项目所必需的

在python内的powershell中转义$_

从 https://www.niftytrader.in/stock-options-chart/sbin 提取 SBIN 股票最大痛苦值的 Python 代码不起作用 - 我错过了什么?

使用 OpenCV 从图像中减go 一条线

从 h264 帧解析数据包时 PyAV 不一致

如何在python中将列表转换为其他格式

pip install mysqlclient 失败为 mysqlclient 运行 setup.py bdist_wheel ... 错误

使用 python 正则表达式匹配日期

如何使用pandas python获取数据框中每列的最大长度

Python 类型提示语法如何/为什么起作用?

如何将 SimpleGUI 与 Python 2.7 和 3.0 shell 集成

所有 Python dunder 方法的列表 - 您需要实现哪些方法才能正确代理对象?

如何将 Matplotlib 图形转换为 PIL Image 对象(不保存图像)

Python,Docker - ascii编解码器无法编码字符

如何在 Python 3.4 中使用 pip 3?