单击按钮,在tkinter窗口中显示图像

The*_*Man 2 python canvas window image tkinter

我需要有关这个程序的帮助,这个程序应该通过点击按钮在新的tkinter窗口中打开图像,但它不会只打开没有图像的新窗口.问题出在哪儿?

使用:python 3.3和tkinter

这是程序:

import sys
from tkinter import *


def button1():
    novi = Toplevel()
    canvas = Canvas(novi, width = 300, height = 200)
    canvas.pack(expand = YES, fill = BOTH)
    gif1 = PhotoImage(file = 'image.gif')
    canvas.create_image(50, 10, visual = gif1, anchor = NW)


mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()

mGui.mainloop()
Run Code Online (Sandbox Code Playgroud)

Tan*_*ash 5

create_image需要一个image参数,而不是visual使用图像,所以visual = gif1不需要,而是需要image = gif1.下一个问题是你需要在gif1某处存储引用,否则它将被垃圾收集,tkinter将无法再使用它.

所以像这样:

import sys
from tkinter import * #or Tkinter if you're on Python2.7

def button1():
    novi = Toplevel()
    canvas = Canvas(novi, width = 300, height = 200)
    canvas.pack(expand = YES, fill = BOTH)
    gif1 = PhotoImage(file = 'image.gif')
                                #image not visual
    canvas.create_image(50, 10, image = gif1, anchor = NW)
    #assigned the gif1 to the canvas object
    canvas.gif1 = gif1


mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()

mGui.mainloop()
Run Code Online (Sandbox Code Playgroud)

Button命名与函数相同的名称也可能不是一个好主意button1,这只会在以后造成混淆.