2

我需要关于这个程序的帮助,这个程序应该通过单击按钮在新的 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()
4

2 回答 2

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()

将您Button的名称命名为与函数相同的名称也可能不是一个好主意button1,这只会在以后引起混乱。

于 2013-04-14T13:42:58.380 回答
0
from tkinter import *
root = Tk()
root.title("Creater window")

def Img():
    r = Toplevel()
    r.title("My image")

    canvas = Canvas(r, height=600, width=600)
    canvas.pack()
    my_image = PhotoImage(file='C:\\Python34\\Lib\idlelib\\Icons\\Baba.gif', master= root)
    canvas.create_image(0, 0, anchor=NW, image=my_image)
    r.mainloop()

btn = Button(root, text = "Click Here to see creator Image", command = Img)
btn.grid(row = 0, column = 0)

root.mainloop()
于 2018-07-09T09:13:59.127 回答