簡體   English   中英

單擊按鈕在tkinter窗口中的圖像

[英]Image in tkinter window by clicking on button

我需要有關該程序的幫助,該程序應通過單擊按鈕在新的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()

create_image需要一個image參數,而不是visual參數才能使用該圖像,因此您需要image = gif1而不是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函數相同的名稱可能也不是一個好主意,這只會在以后引起混亂。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM