为什么after()方法不能在multi-for循环中工作?

2024-05-19 12:24:49 发布

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

我将在multiforloop中使用after()方法。计划是以1秒的间隔打印每一个组合文本。你知道吗

但它直接运行到最后,只打印最后一个组合文本。我怎样才能解决这个问题?你知道吗

这是我的密码:

# -*- coding: utf-8 -*-

from Tkinter import *
import time

FirstList = ["1", "2", "3", "4"]
SecondList = ["a", "b", "c", "d", "e", "f"]
ThirdList = ["A" , "B" , "C"]

root = Tk()
root.title("Program")
root['background'] ='gray'

def command_Print():
    for i in range(0, len(FirstList), 1):
        for j in range(0, len(SecondList), 1):
            for k in range(0, len(ThirdList), 1):
                PrintText = FirstList[i] + SecondList[j] + ThirdList[k]
                Labelvar.set(PrintText)
                Label0.after(1000, lambda: command_Print)

Labelvar = StringVar()
Labelvar.set(u'original value')
Frame0 = Frame(root)
Frame0.place(x=0, y=0, width=100, height=50)
Label0 = Label(Frame0, textvariable=Labelvar, anchor='w')
Label0.pack(side=LEFT)

Frame_I = Frame(root)
Frame_I.place(x = 100, y = 0, width=100, height=70)
Button_I = Button(Frame_I, text = "Button" , width = 100, height=70, command = command_Print)
Button_I.place(x=0, y=0)
Button_I.grid(row=0, column=0, sticky=W, pady=4)
Button_I.pack()

root.mainloop()

Tags: inforlenrangebuttonrootframecommand
1条回答
网友
1楼 · 发布于 2024-05-19 12:24:49

如果我知道你想要什么,你只需要你名单上的卡特斯乘积。您可以使用itertools来实现这一点,而不是像您那样使用嵌套的forloop,无需重新发明轮子,因为itertools已经内置了这个功能,而且它更干净。你知道吗

给你:(未测试)

import itertools

PRODUCTS = itertools.product(FirstList, SecondList, ThirdList)

def show_next_product():

     try:
        LabelVar.set(next(PRODUCTS))
        root.last_after = root.after(1000, show_next_product)
     except StopIteration:
        LabelVar.set("Out of products.")
        root.after_cancel(root.last_after)

而且,StringVar似乎没有必要。除非你用trace方法为StringVar做些什么,否则我从来没有看到过诚实地使用它们的意义。你知道吗

您可以使用Label0['text'] = 'newtext'直接更改文本,但这当然是个人喜好。:)

相关问题 更多 >