Image in tkinter window by clicking on button

别等时光非礼了梦想. 提交于 2020-01-15 03:09:12

问题


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?

Using: python 3.3 and tkinter

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

回答1:


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.

So something like this:

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

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.




回答2:


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


来源:https://stackoverflow.com/questions/15999661/image-in-tkinter-window-by-clicking-on-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!