Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用按钮打开带有图像的窗口_Python_Image_Tkinter_Python Imaging Library - Fatal编程技术网

在Python中使用按钮打开带有图像的窗口

在Python中使用按钮打开带有图像的窗口,python,image,tkinter,python-imaging-library,Python,Image,Tkinter,Python Imaging Library,我想打开一个包含图像的新窗口。我不知道如何做到这一点。目前,我的代码打开了一个普通窗口,窗口上有一个按钮,上面写着“显示图像” from tkinter import * from PIL import ImageTk, Image root = Tk() root.configure(background = "black") obrazek = ImageTk.PhotoImage(Image.open("dn.jpg")) def clic

我想打开一个包含图像的新窗口。我不知道如何做到这一点。目前,我的代码打开了一个普通窗口,窗口上有一个按钮,上面写着“显示图像”

from tkinter import * 
from PIL import ImageTk, Image




root = Tk()
root.configure(background = "black")
obrazek = ImageTk.PhotoImage(Image.open("dn.jpg"))
def click():
    
    MyLabel = Label(root, image = obrazek)
    Tk()
    MyLabel.pack()


myButton = Button(root, text = "Wyjście", command = click, fg = "white", bg = "#000000")
myButton.pack()


mainloop()

这是最简单的工作示例

您只能使用
Tk()
来创建主窗口。对于其他窗口,您必须使用
Toplevel
。当变量ie.
top
中有它时,必须将其用作
Label
(或其他小部件)中的第一个参数,以便在此窗口中显示小部件

顺便说一句:

维基百科图片:


编辑:


我希望您没有在函数内部创建
PhotoImage
,因为
PhotoImage
中有一个错误,当图像被分配给函数中的局部变量时,它会从内存中删除图像。然后你可以看到空的图像。必须将其分配给全局变量或某个对象,即
my_label.img=image

不要使用
Tk()
两次,使用
Toplevel
而不是如何在新按钮弹出窗口中显示图片?@Paramonow您希望按钮具有图像还是窗口?我想在按下按钮后显示图片,对不起,不准确
#from tkinter import *  # PEP8: `import *` is not preferred 

import tkinter as tk
from PIL import ImageTk, Image

# --- functions ---

def click():
    top = tk.Toplevel()
    my_label = tk.Label(top, image=my_image)
    my_label.pack()

# --- main ---

root = tk.Tk()
#root.configure(background="black")  # PEP8: without spaces around `=`

my_image = ImageTk.PhotoImage(Image.open("lenna.png"))  # PEP8: english names

my_button = tk.Button(root, text="Wyjście", command=click)  # PEP8: lower_case_names for variables
my_button.pack()

root.mainloop()