如何在显示实验室之前暂停代码

2024-10-06 12:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的代码中,我试图为一个青蛙游戏制作一个加载屏幕,但是由于某些原因,我遇到了一个问题,我显示一张图片,然后在上面显示一个标签之前执行.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()

Tags: 代码importmastertimetkinterplacesleep标签
1条回答
网友
1楼 · 发布于 2024-10-06 12:27:17

在启动window.mainloop()之前使用time.sleep(1)时,仅在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(...).place(...)方法—Tkinter会忽略第一个方法(.pack(...)) 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的坐标。你知道吗

相关问题 更多 >