【问题标题】:How do i pause my code before displaying the label如何在显示标签之前暂停我的代码
【发布时间】:2019-06-15 18:48:05
【问题描述】:

在我的代码中,我正在尝试为青蛙游戏制作加载屏幕,但由于某种原因,我遇到了一个问题,即显示图片,然后执行 .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()

【问题讨论】:

  • 你睡了一秒钟。你试过睡一秒钟以上吗?
  • 您的 sleep() 出现在 mainloop() 之前,但 GUI before mainloop(). You need something like the after() 方法不会发生任何事情。
  • 使用 root.after() 方法代替睡眠。

标签: python tkinter


【解决方案1】:

当你在启动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(...) 方法 - 第一个(.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 更改坐标。

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    相关资源
    最近更新 更多