在tkinter窗口的图象通过点击按钮 [英] Image in tkinter window by clicking on button

查看:612
本文介绍了在tkinter窗口的图象通过点击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help about this program, this program should open image in new tkinter window by clicking on button, but it doesn't it just opens new window without image. Where is the problem?

使用:python 3.3和tkinter

Using: python 3.3 and tkinter

/ p>

This is program:

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


推荐答案

create_image 需要 image 参数,而不是 visual 来使用图片,所以代替 visual = gif1 ,您需要 image = gif1 。下一个问题是你需要将 gif1 引用存储在某个地方,否则它会被垃圾收集,tkinter将无法再使用它。

create_image needs a image argument, not visual to use the image, so instead of visual = gif1, you need image = gif1. The next problem is that you need to store the gif1 reference somewhere or else it'll get garbage collected and tkinter won't be able to use it anymore.

这样的东西:

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 ,稍后会导致混乱。

It's also probably not a good idea to name your Button the same name as the function button1, that'll just cause confusion later on.

这篇关于在tkinter窗口的图象通过点击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆