【问题标题】:tkinter (py3) - change image labels, inside functions, in real timetkinter (py3) - 实时更改图像标签、内部函数
【发布时间】:2016-04-13 15:35:36
【问题描述】:

我正在学习使用 tkinter,我尝试在咖啡机上设置 4 个按钮,每个按钮都会创建一个新窗口,该窗口会按顺序显示图像,就像幻灯片一样。我所做的不起作用,因为它只显示幻灯片中的最后一张图像,而忽略了其余的。在 python 2.7 中,我可以通过在每次配置标签后在控制台中不打印任何内容来修复它,但它似乎不起作用。如果您能告诉我为什么会发生这种情况,和/或如何解决它,我们将不胜感激。

(PS 我知道我的代码可能非常丑陋/效率低下,但请记住,我对 tkinter 很陌生,所以我只关心它是否有效)。

def Latte():
    global Grind
    global Hot_Water
    global Cocoa_Poweder
    global Steamed_Milk
    global Foamed_Milk
    global LattePhoto

    MakingCoffee=Toplevel(Test, width=200, height=200)
    MakingCoffee.wm_title("Latte")
    MakingCoffee.iconbitmap("Photos\Latte.ico")

    photolabel= Label(MakingCoffee,image=Grind)
    photolabel.pack()
    time.sleep(2)
    photolabel.configure(image=Hot_Water)
    time.sleep(2)
    photolabel.configure(image=Steamed_Milk)
    time.sleep(4)
    photolabel.configure(image=Foamed_Milk)
    time.sleep(1)
    photolabel.configure(image=LattePhoto)
    time.sleep(2)
    MakingCoffee.destroy()

【问题讨论】:

  • 最好在此处发布代码中最关键和相关的部分,而不是链接到外部资源。
  • 代码中最关键的部分是函数中的部分。

标签: python python-3.x tkinter


【解决方案1】:

以下是实现这项工作的一种方法的一小部分示例。您可以根据需要进行重组。该列表只是为了让我可以遍历它以显示更改。您不需要原始代码中的所有这些全局变量。它们已经是全局变量,您不会尝试重新分配它们,因此这是一种冗余。您至少可以将大约 50% 的代码分解为可重用。你可以把这个做成一个类,做成一个“工厂类”,用不同的咖啡制作不同类型的幻灯片,然后你也可以在这里去掉global

from tkinter import *
import tkinter
import time

Test = tkinter.Tk()
Test.wm_title("Coffee Store")
Test.resizable(0, 0)

americano_images = [
    PhotoImage(file='1.gif'), 
    PhotoImage(file='2.gif'), 
    PhotoImage(file='3.gif')
]
AFTER = None

AmericanoPhoto= PhotoImage(file="1.gif")

def switch_images(im_list, label, index=0):

    global AFTER
    label.configure(image=im_list[index])
    if index != len(im_list) - 1:
        index += 1
    else:
        index = 0
    AFTER = Test.after(1000, lambda: switch_images(im_list, label, index))

def Americano():

    MakingCoffee=Toplevel(Test, width=200, height=200)
    MakingCoffee.wm_title("Americano")

    photolabel= Label(MakingCoffee)
    photolabel.pack_propagate(0)
    photolabel.pack()
    after = switch_images(americano_images, photolabel)
    cancel = Button(MakingCoffee, text='Kill Slideshow', 
        command=lambda: Test.after_cancel(AFTER))
    cancel.pack(fill=X, expand=1)

B1= Button(Test, text='BUTTON', command=Americano)
B1.grid(row=0,column=0)

Test.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多