首页 > 解决方案 > 如何在显示标签之前暂停我的代码

问题描述

在我的代码中,我正在尝试为青蛙游戏制作加载屏幕,但由于某种原因,我遇到了一个问题,即我显示一张图片,然后在.sleep在其顶部显示标签之前执行该功能,但是它同时显示了它们同时它只是在它应该运行的 1 秒后运行代码,有人可以帮忙吗?

下面是我的代码:

from tkinter import *

import tkinter as tk

import time

window = Tk()
window.geometry("1300x899")

LoadingScreen = PhotoImage(file = "FroggerLoad.gif")

Loading = Label(master = window, image = LoadingScreen)

Loading.pack()

Loading.place(x = 65, y = 0)

time.sleep(1)

FroggerDisplay = Label(master = window, font ("ComicSans",100,"bold"),text = "Frogger")
FroggerDisplay.pack()

FroggerDisplay.place(x = 500, y = 300)

window.mainloop()

标签: pythontkinter

解决方案


time.sleep(1)在启动前使用时window.mainloop(),窗口仅在 1 秒后创建,FroggerDisplay标签将与其同时创建。所以,你现在不能用time.sleep(seconds)

但是,您可以使用window.after(ms, func)方法,并将 和 之间的所有代码放入函数time.sleep(1)window.mainloop()。请注意,与您不同,time.sleep(seconds)您必须将时间window.after(第一个参数)设置为毫秒

这是编辑后的代码:

from tkinter import *


def create_fd_label():
    frogger_display = Label(root, font=("ComicSans", 100, "bold"), text="Frogger")  # create a label to display
    frogger_display.place(x=500, y=300)  # place the label for frogger display

root = Tk()  # create the root window
root.geometry("1300x899")  # set the root window's size

loading_screen = PhotoImage(file="FroggerLoad.gif")  # create the "Loading" image
loading = Label(root, image=loading_screen)  # create the label with the "Loading" image
loading.place(x=65, y=0)  # place the label for loading screen

root.after(1000, create_fd_label)  # root.after(ms, func)
root.mainloop()  # start the root window's mainloop

PS:1)为什么同时使用.pack(...)then.place(...)方法 - 第一个(.pack(...)此处)将被 Tkinter 忽略。
2) 最好使用Canvas小部件来创建游戏 - 与标签不同,它支持透明度并且更易于使用。例如:

from tkinter import *


root = Tk()  # create the root window
root.geometry("1300x899")  # set the root window's size
canv = Canvas(root)  # create the Canvas widget
canv.pack(fill=BOTH, expand=YES) # and pack it on the screen

loading_screen = PhotoImage(file="FroggerLoad.gif")  # open the "Loading" image
canv.create_image((65, 0), image=loading_screen)  # create it on the Canvas

root.after(1000, lambda: canv.create_text((500, 300),
                                          font=("ComicSans", 100, "bold"),
                                          text="Frogger"))  # root.after(ms, func)
root.mainloop()  # start the root window's mainloop

注意:您可能需要使用 更改坐标Canvas


推荐阅读