我的计算机上具有GIF文件路径的变量,在main()循环中,有一个供GIF在循环中运行的类和一个Worker类。 还要从cmd提示符下执行它。
该程序的执行应该只打印8倍所选水果的类型,并在Tkinter中显示该水果的GIF,当您输入“确定”时,GIF应该退出,程序等待下一个输入(另一种水果)进行操作。同样的事情。
一切正常,直到第二次尝试。也就是说,它会打印出8倍水果很好但没有GIF显示的水果。如果输入'ok',则会报告
“线程Thread中的异常”
和
“ RuntimeError:主线程不在主循环中”错误。
我从http://code.activestate.com/recipes/580708-tkinter-animated-gif/下载了AnimatedGIF类代码,但是我发现只有一半能使GIF循环播放,所以我将其切碎了。
猜猜我需要队列模块或线程after()方法,但我不知道要实现它们。
#! python3
fruit = [ 'apple', 'peach', 'orange', 'grape', 'lemon', 'banana',
'strawberry', 'coconut' ]
app = r"C:\Users\User\Desktop\folder za python fajlove\Apple.gif"
pea = r"C:\Users\User\Desktop\folder za python fajlove\Peach.gif"
ora = r"C:\Users\User\Desktop\folder za python fajlove\Orange.gif"
gra = r"C:\Users\User\Desktop\folder za python fajlove\Grape.gif"
lem = r"C:\Users\User\Desktop\folder za python fajlove\Lemon.gif"
ban = r"C:\Users\User\Desktop\folder za python fajlove\Banana.gif"
stw = r"C:\Users\User\Desktop\folder za python fajlove\Strawberry.gif"
coc = r"C:\Users\User\Desktop\folder za python fajlove\Coconut.gif"
GIF = [ app, pea, ora, gra, lem, ban, stw, coc ]
def main():
print('Enter the type of fruit you like to see')
inpuT = input()
while inpuT not in fruit:
print('Enter the type of fruit you like to see')
inpuT = input()
a = fruit.index(inpuT)
for x in fruit:
print( fruit[a] + ' is nice!!!')
import tkinter as tk
from tkinter import PhotoImage
from tkinter import Label
import threading
from PIL import Image, ImageTk
#-----------------------------------------------------------
class AnimatedGIF(Label, object):
def __init__(self, master, path, forever=True):
self._master = master
self._loc = 0
self._forever = forever
self._is_running = False
im = Image.open(path)
self._frames = []
i = 0
try:
while True:
photoframe =
ImageTk.PhotoImage(im.copy().convert('RGBA'))
self._frames.append(photoframe)
i += 1
im.seek(i)
except EOFError: pass
self._last_index = len(self._frames) - 1
try:
self._delay = im.info['duration']
except:
self._delay = 100
super(AnimatedGIF, self).__init__(master,
image=self._frames[0])
def start_animation(self, frame=None):
if self._is_running: return
if frame is not None:
self._loc = 0
self.configure(image=self._frames[frame])
self._master.after(self._delay, self._animate_GIF)
def _animate_GIF(self):
self._loc += 1
self.configure(image=self._frames[self._loc])
if self._loc == self._last_index:
if self._forever:
self._loc = 0
self._callback_id =
self._master.after(self._delay, self._animate_GIF)
else:
self._callback_id = self._master.after(100,
self._animate_GIF)
def pack(self, start_animation=True, **kwargs):
if start_animation:
self.start_animation()
super(AnimatedGIF, self).pack(**kwargs)
class Worker(threading.Thread):
def run(self):
global root
root = tk.Tk()
win = AnimatedGIF(root, GIF[a])
win.pack()
root.mainloop()
w = Worker()
w.start()
novo = input()
if novo == 'ok':
root.quit()
while True:
main()