我一直在努力让一个简单的Tkinter画布显示一个图像使用创建图像。我读过很多线程,它们说您需要在任何函数或类之外创建对对象的引用,否则图像对象将被垃圾收集。不幸的是,我还是不能让这个工作。下面是我的代码。忽略所有颜色-我用它们来说明框架和画布在窗口上的位置。
-柯克

import Tkinter as tk
from PIL import Image
from PIL import ImageTk

imageList = []
image = Image.open('len_std.jpg')

#event handlers
def hit_sel_click():
    imageList = []
    test_image = ImageTk.PhotoImage(image)
    imageList.append(cnv_hits.create_image(0,0,
                 image=test_image))

#start root
root = tk.Tk()
root.title('SimView')
root.resizable(width=False, height=False)

#target/control variables
hit_sel = tk.StringVar() #holds radio button with activity level

#build GUI
frm_hits = tk.Frame(root, height=800, width=200, bg='#FF0000')
frm_hits.grid(rowspan=3, sticky=tk.W+tk.N+tk.S+tk.E)

tk.Label(frm_hits, text='Activity:').grid()
tk.Radiobutton(frm_hits, text='Low', variable=hit_sel, value='Low',
               command=hit_sel_click).grid(sticky=tk.W)
tk.Radiobutton(frm_hits, text='Medium', variable=hit_sel, value='Medium',
                command=hit_sel_click).grid(sticky=tk.W)
tmp = tk.Radiobutton(frm_hits, text='High', variable=hit_sel,value='High',
                 command=hit_sel_click)
tmp.grid(sticky=tk.W)
tmp.select()

frm_hit_list = tk.Frame(frm_hits, bg='#002288')
frm_hit_list.grid(sticky=tk.W+tk.N+tk.E+tk.S)

scrl_hits = tk.Scrollbar(frm_hit_list, orient=tk.VERTICAL)
scrl_hits.grid(row=0, column=1, sticky=tk.N+tk.S)

cnv_hits = tk.Canvas(frm_hit_list, bg='#888800',width=200, height=200,
                     yscrollcommand=scrl_hits.set)
cnv_hits.grid(row=0, column=0, sticky=tk.W+tk.N+tk.E+tk.S)

scrl_hits.config(command=cnv_hits.yview)

root.mainloop()

最佳答案

您正在使用test_image绘制cnv_hits的图像。是的,但是您忘记了test_imagehit_sel_click()方法的本地;这意味着它对您的主程序不可用。
要解决此问题,您有两个选择:
test_image内声明globalhit_sel_click()
或者在声明test_image = ImageTk.PhotoImage(image)之前运行hit_sel_click()
注:
对于第一种情况,您需要在root = tk.Tk()之前运行hit_sel_click()
如果您选择第二个选项,则需要在root = tk.Tk()之前运行test_image = ImageTk.PhotoImage(image)
如果不这样做,程序将引发RuntimeError异常。

10-05 20:24