Python代码问题,应用程序已被破坏T

2024-06-12 11:47:46 发布

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

我正在制作一个Tkinter图形用户界面,除了调用图像什么都不做——当然,我一直在努力寻找合适的Tkinter文档。在

我的代码中有一行似乎不能按要求执行——我想调用字典中的所有值,在调用下一个值之前,为每个值单独打印并拉取一个同名的图像。我试过了dict.itervalues()和dict.值()似乎什么都搞不清楚。。。在

总之,下面是一个片段:

for key in ansDict.iterkeys(): #using the iterkeys function... kind of
    x=key

    root = tk.Tk() # root window created (is this in the right place?)
    root.title('C H E M I S T R Y   A B C\'s')

    frameAns=tk.Frame(root)
    frameAns.grid(row=0, column=0, sticky=tk.NW)

    for i in range(len(ansDict[x])):
        print '-->' + ansDict[x][i]

    for value in ansDict.itervalues(): #This is the most important part

        for i in range(len(value)): #pulls value list from dictionary named ansDict
            picRef1 = Image.open(value[i] + '.jpg') #calls image file by the same name using PIL
            photo1 = ImageTk.PhotoImage(picRef1, master=root)

            button1 = tk.Button(frameAns, compound=tk.TOP, image=photo1, text=str(value[i]) + '\nClose me!', bg='white') #pulls up button onto which the image is pasted
            button1.grid(sticky=tk.NW, padx=2, pady=2) #places button on grid
            button1.image=photo1

            root.mainloop()

最后,在最后,它提取了一到两个图像,然后我得到了以下错误:

TclError:无法调用“image”命令:应用程序已被销毁

我不知道怎么了。我不能移动图像命令,我需要“保存”它,这样它就不会被破坏。我知道这里还有其他的代码错误,但是我认为如果我弄清楚我得到的TclError,我就可以纠正其他所有的错误。在

如果有更简单的方法来做这一切请一定告诉!在


Tags: thein图像imageforisvalue错误
3条回答

你好像没有想到Event-driven programming。您应该创建一个完整的GUI,用小部件填充它,设置事件,然后进入无限循环。GUI应该根据事件到函数的绑定调用回调函数。所以程序的那些部分应该只调用一次:root = tk.Tk()root.mainloop()。在

编辑:添加了事件驱动编程“idea example”。在

from Tkinter import *

master = Tk()

def callback():
    print "click!"

b = Button(master, text="OK", command=callback)
b.pack()

mainloop()

我四处寻找解决这个问题的好办法,但还没有找到合适的解决办法。看着特金特.py类它看起来像Imagedel值是:

def __del__(self):
    if self.name:
        try:
            self.tk.call('image', 'delete', self.name)
        except TclError:
            # May happen if the root was destroyed
            pass

这意味着如果你想进行一次野蛮的黑客攻击,你可以按照jtp的链接设置一个照片图像。在

^{pr2}$

然后,在程序退出之前,您可以执行以下黑客操作:

photo.name = None

这将阻止它在PhotoImage删除中尝试清理自己,并防止在del方法中调用异常。我不建议你这样做,除非你背对着墙,而且你别无选择。在

我会继续调查这个问题,如果我找到更好的解决方案,我会用一个更好的解决方案来编辑这篇文章(希望有人能在那之前给出正确的解决方案)。在

这里有一种可能,尽管它的结构与您的示例不同。它将四个100像素的正方形图像堆叠在一起。我相信你需要为每个图像对象保留一个单独的引用,所以我把它们放在了images字典中。在

from Tkinter import *
import os
from PIL import Image, ImageTk

image_names = { '1':'one','2':'two','3':'three','4':'four' }
images = {}

root = Tk()
root.title("HELLO")
frm = Frame(root)

for v in image_names.itervalues():
   images[v] = {}
   images[v]['i']  = Image.open("%s%s.jpg" % (os.path.dirname(__file__), v))
   images[v]['pi'] = ImageTk.PhotoImage(images[v]['i'])
   images[v]['b']  = Button(frm, image=images[v]['pi'])
   images[v]['b'].pack()

frm.pack()

mainloop()

这里是讨论PhotoImage类的一个很好的链接。在

http://effbot.org/tkinterbook/photoimage.htm

相关问题 更多 >