在使用Tkinter~Python中的事件时,在For循环内部执行线程

2024-04-19 21:22:05 发布

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

尝试一个场景,在这个场景中,我希望在基于线程机制的for循环中继续[for syncing/wait mechanism],如下面的代码所示。你知道吗

#!/tools/bin/python

# Global Import Variables
import Tkinter
from Tkinter import *
import subprocess
import shlex
import os 
from PIL import Image, ImageTk
import time
import string
import threading

class test_template:
    def __init__(self, master):
        self.master = master
        self.next_button = None
        self.fruit_lbl = None
        self.yes_button = None
        self.no_button = None
        self.yes_no_button_done = threading.Event()

        # For Loop Goes From 0 To 10
        for i in range (10):
            if not (self.fruit_lbl):
                self.fruit_lbl = Label(root, text="Do You Want To Change The Color Of Fruit %d"%i)
                self.fruit_lbl.grid(row=1, column=0)
            if not (self.yes_button): 
                self.yes_button = Button(root, background="lawn green", activebackground="forest green", text="YES", command=self.yes_button_code).grid(row=2, column=1)    
            if not (self.no_button): 
                self.no_button = Button(root, background="orange red", activebackground="orangered3", text="NO", command=self.no_button_code).grid(row=2, column=2)    

            while not self.yes_no_button_done.isSet():
                self.yes_no_button_done.wait()

    def yes_button_code(self):
        print "Inside YES Button Config"
    def no_button_code(self):
        print "Inside No Button Config"
        self.yes_no_button_done.set()

# Top Local Variables
root = Tk()
#root.configure(background='black')

# Top Level Default Codes
my_gui = test_template(root)

root.mainloop()

它就像for循环需要等待,直到我按下Yes或No,直到那时while循环应该等待事件集。你知道吗

但不知何故,线程/等待机制并没有很好地工作,即只要我启动代码,它就会进入while循环并失控。上面的代码有什么遗漏吗?分享你的评论!!你知道吗


Tags: no代码importselfnonefornotcode
1条回答
网友
1楼 · 发布于 2024-04-19 21:22:05

如果我没有正确理解你,我认为你根本不需要使用线程。考虑以下几点:

from Tkinter import *


class test_template:

    def __init__(self, master):
        self.master = master
        self.loop_count = IntVar()
        self.loop_count.set(1)

        l = Label(self.master, text='Change colour of fruit?')
        l.pack()
        count = Label(self.master, textvariable = '%s' % self.loop_count)
        count.pack()
        yes = Button(self.master, text = 'YES', command = self.loop_counter)
        yes.pack() 
        no = Button(self.master, text = 'NO', command = self.loop_counter)
        no.pack()

    def loop_counter(self):
        if self.loop_count.get() == 10:
            print 'Finished'
            self.master.quit()
        else:
            self.loop_count.set(self.loop_count.get()+1)
            print self.loop_count.get()


root = Tk()
GUI = test_template(root)
root.mainloop()

让我知道你的想法。你知道吗

干杯, 卢克

相关问题 更多 >