尝试一个场景,我希望继续基于线程机制[用于同步/等待机制]的for循环,如下面的代码所示。
#!/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循环并变得混乱。我在上面的代码中遗漏了什么吗?分享您的评论!!
答案 0 :(得分:0)
如果我正确地提出你,我认为你根本不需要使用线程。请考虑以下事项:
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()
让我知道你的想法。
干杯, 路加