首页 > 解决方案 > Tkinter 标签未执行

问题描述

我正在使用 Python 中的 tkinter 模块编写应用程序。我遇到问题的代码部分是:

def sceneChange():    
    global num
    num = num + 1
    currentScene = scenes[num]
    global label
    label.destroy()
    label = tk.Label(window, image = currentScene)
    label.pack()
    time1 = dt.datetime.utcnow().minute + dt.datetime.utcnow().second / 60 
    testTime = time1 + 4.44 / 60 # ~5 secs in the future
    while dt.datetime.utcnow().minute + dt.datetime.utcnow().second / 60 < testTime: 
        pass
    label.destroy()
    num = num + 1
    currentScene = scenes[num]
    label = tk.Label(window, image = currentScene)
    label.pack()

用于:

b = tk.Button(label, text = "Start", command = sceneChange, height = 1, width = 10)
b.place(x = 440, y = 48)

while 循环之前的 label.pack 命令未显示在我的窗口中。我试图让它显示 5 秒钟,然后将图像切换到其他东西。但是,事实并非如此。所有帮助将不胜感激。如果我在问题的格式上做错了什么,请告诉我,以便我改进:)。整个代码如下:

import tkinter as tk
import datetime as dt

window = tk.Tk()
window.title("Game")
scenes = [tk.PhotoImage(file = "TitleScreen.gif"), tk.PhotoImage(file = "ControlsScreen.gif"), tk.PhotoImage(file = "game.gif")]
num = 0
currentScene = scenes[num]
label = tk.Label(window, image = currentScene)


def sceneChange():
    global num
    num = num + 1
    currentScene = scenes[num]
    global label
    label.destroy()
    label = tk.Label(window, image = currentScene)
    label.pack()
    time1 = dt.datetime.utcnow().minute + dt.datetime.utcnow().second / 60 # current time
    testTime = time1 + 4.44 / 60 # ~5 secs in the future
    while dt.datetime.utcnow().minute + dt.datetime.utcnow().second / 60 < testTime: 
        pass
    label.destroy()
    num = num + 1
    currentScene = scenes[num]
    label = tk.Label(window, image = currentScene)
    label.pack()


label.pack()
b = tk.Button(label, text = "Start", command = sceneChange, height = 1, width = 10)
b.place(x = 440, y = 48)
b1 = tk.Button(label, text = "Quit", command = exit, height = 1, width = 10)
b1.place(x = 440, y = 78)

label.mainloop()

标签: pythontkinter

解决方案


您应该使用after()函数而不是while循环,因为使用 while 循环会导致窗口冻结,直到循环结束。

如果你想知道如何使用after()

去这个帖子


现在,如何实现一张图片显示 5 秒?

这是一个例子。

from tkinter import *

root = Tk()

root.geometry("250x250")

Img1 = PhotoImage(file="img1.png")     # Image 1
Img2 = PhotoImage(file="img2.png")      # Image 2

L = Label(root, image=Img1)
L.pack()

# The image will change in 5000ms ( 5secs )
root.after( 5000, lambda: L.config(image=Img2) )

root.mainloop()

推荐阅读