如何将png图片添加到tinkter python窗口?

时间:2017-01-27 16:54:54

标签: python image tkinter png

我有一个窗口,我正在尝试添加图像。到目前为止,窗口由标签输入框和按钮组成。我想在标签下方但在输入框按钮上方添加图像。这是我的代码:

    master = Tk()
    master.wm_title("Lightning Parties")
    master.configure(background='lightgreen')
    Label(master, text="Staff Login", fg='black', bg='lightgreen', font=    ('comicsans', 14)).grid()
    Label(master, text="Please enter the password ", fg='black', bg='lightgreen', font=('comicsans', 12)).grid(row=7)

    Password= Entry(master)

    Password.grid(row=7, column=1)

    Button(master, text='Login', command=validateStaff, fg='black', bg='white', font=('comicsans', 12)).grid(row=10, column=1, sticky=W, pady=4)

我要添加的图片的文件名为'sonic.png'。

1 个答案:

答案 0 :(得分:0)

您可以使用所需的图片创建PhotoImage,这适用于.png.gif以及许多其他图片文件。

只需将图片放在Label中,然后将Label放入grid

from tkinter import *

master = Tk()
master.wm_title("Lightning Parties")
master.configure(background='lightgreen')
Label(master, text="Staff Login", fg='black', bg='lightgreen', font=    ('comicsans', 14)).grid()
Label(master, text="Please enter the password ", fg='black', bg='lightgreen', font=('comicsans', 12)).grid(row=7)

Password= Entry(master)    
Password.grid(row=7, column=1)

my_image = PhotoImage(master = master, file = "Your_image.png") # your image
label = Label(master, image = my_image) # put the image on a label
label.grid(row = 6, column = 0, columnspan = 2) # put the label in the grid

Button(master, text='Login', command=validateStaff, fg='black', bg='white', font=('comicsans', 12)).grid(row=10, column=1, sticky=W, pady=4)

另外@Brenda评论你帖子的人只是想帮助你:)当我第一次加入SO时,我的一些帖子被投了票,你应该从错误中吸取教训而不是防守:)