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()
解决方案
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
。
推荐阅读
- linux - LanguageTool Java 应用程序作为 systemd 服务运行。`--languagemodel` 参数被忽略
- wpf - WPF:Prism Window XAML 的 Topmost 属性的 DataTrigger
- raku - 乐中的有理数
- python - 如何在多列内切片?
- node.js - nodejs http客户端卡在高流量
- java - 如何使用多对多字段本地查询 WHERE IN?
- ballerina - 生产者可以发送 kafka 消息的标头吗?
- ios - iOS Firestore 应用程序在模拟器上运行,但不在手机上
- javascript - 反应数据表组件,将点击行的信息传递到模态
- ansible - Ansible Regex:从命令中获取整数并传递给其他命令以运行