2016-10-07 67 views
0

我已经改编了一个python脚本来显示图像幻灯片。原始脚本可以在https://github.com/cgoldberg/py-slideshow来自幻灯片的文件输出列表

我希望能够记录显示的每个图像的文件名,以便我可以更容易地调试任何错误(即删除不兼容的图像)。

我试图在def get_image_paths函数中包含一个命令来将文件名写入文本文件。但是,这并没有奏效。我的代码出现在下面 - 任何帮助表示赞赏。

import pyglet 
import os 
import random 
import argparse 

window = pyglet.window.Window(fullscreen=True) 

def get_scale(window, image): 
    if image.width > image.height: 
     scale = float(window.width)/image.width 
    else: 
     scale = float(window.height)/image.height 
    return scale 


def update_image(dt): 
    img = pyglet.image.load(random.choice(image_paths)) 
    sprite.image = img 
    sprite.scale = get_scale(window, img) 
    if img.height >= img.width: 
     sprite.x = ((window.width/2) - (sprite.width/2)) 
     sprite.y = 0 
    elif img.width >= img.height: 
     sprite.y = ((window.height/2) - (sprite.height/2)) 
     sprite.x = 0 
    else: 
     sprite.x = 0 
     sprite.y = 0 
    window.clear() 

thefile=open('test.txt','w') 
def get_image_paths(input_dir='.'): 
    paths = [] 
    for root, dirs, files in os.walk(input_dir, topdown=True): 
     for file in sorted(files): 
      if file.endswith(('jpg', 'png', 'gif')): 
       path = os.path.abspath(os.path.join(root, file)) 
       paths.append(path) 
      thefile.write(file) 
    return paths 


@window.event() 
def on_draw(): 
    sprite.draw() 


if __name__ == '__main__': 
    parser = argparse.ArgumentParser() 
    parser.add_argument('dir', help='directory of images', 
         nargs='?', default=os.getcwd()) 
    args = parser.parse_args() 
    image_paths = get_image_paths(args.dir) 
    img = pyglet.image.load(random.choice(image_paths)) 
    sprite = pyglet.sprite.Sprite(img) 
    pyglet.clock.schedule_interval(update_image, 3) 
    pyglet.app.run() 
+0

最好使用'logging'模块写入日志文件。 – furas

+0

也许你必须关闭文件。 – furas

+0

'sprite'永远不会在'update_image'中声明 - 这是一个编程错误还是你剥离代码的结果? – Torxed

回答

1

系统不必一次写入文件,但它可以保持文本在缓冲区中并保存在关闭文件时。所以可能你必须关闭文件。

或者您可以在每之后使用thefile.flush()一次将新文本从缓冲区发送到文件。

0

我最终宣布将随机图像选择为一个变量,然后我写入一个txt文件。与变化相关的代码如下所示:

thefile=open('test.txt','w') 

def update_image(dt): 
pic = random.choice(image_paths) 
img = pyglet.image.load(pic) 
thefile.write(pic+'\n') 
thefile.flush() 
sprite.image = img 
sprite.scale = get_scale(window, img) 
if img.height >= img.width: 
    sprite.x = ((window.width/2) - (sprite.width/2)) 
    sprite.y = 0 
elif img.width >= img.height: 
    sprite.y = ((window.height/2) - (sprite.height/2)) 
    sprite.x = 0 
else: 
    sprite.x = 0 
    sprite.y = 0 
window.clear() 

谢谢@furas指着我在正确的方向有关的日志文件,并刷新该缓冲区,以一定的捕捉到所有实例。