Python 2.7:tkinter,无法将图像添加到GUi

时间:2018-05-21 17:58:24

标签: python macos tkinter

Python 2.7 Macbook OSX

我正在尝试将图像添加到我的tkinter GUI,但我无法。我能够自己运行下面的脚本并在GUI上有一个图像:

from Tkinter import *

root = Tk()
logo = PhotoImage(file="tkinter2.gif")

w1 = Label(root, image=logo).pack(side="right")

root.mainloop()

但是当我尝试添加相同的行时:

logo = PhotoImage(file="tkinter2.gif")
w1 = Label(root, image=logo).pack(side="right")

我的脚本似乎冻结了,这是我没有添加行的脚本,运行正常:

#!/usr/bin/python

from Tkinter import *

root = Tk()
root.title('Login')
root.geometry('450x300')

root.config(bg='light blue')

def clear_widget(event):

    if username_box == root.focus_get() and username_box.get() == 'Enter Username':
        username_box.delete(0, END)
    elif password_box == password_box.focus_get() and password_box.get() == '     ':
        password_box.delete(0, END)

def repopulate_defaults(event):

    if username_box != root.focus_get() and username_box.get() == '':
        username_box.insert(0, 'Enter Username')
    elif password_box != root.focus_get() and password_box.get() == '':
        password_box.insert(0, '     ')

def login(*event):

    username = username_box.get()
    password = password_box.get()

    root.destroy()
    TEST.runKcommands(username, password)

rows = 0
while rows < 10:
    root.rowconfigure(rows, weight=1)
    root.columnconfigure(rows, weight=1)
    rows += 1

username_box = Entry(root,bg="light blue", fg="blue")
username_box.insert(0, 'Enter Username')
username_box.bind("<FocusIn>", clear_widget)
username_box.bind('<FocusOut>', repopulate_defaults)
username_box.grid(row=1, column=5, sticky='NS')

password_box = Entry(root, show='*',bg="light blue", fg="blue")
password_box.insert(0, '     ')
password_box.bind("<FocusIn>", clear_widget)
password_box.bind('<FocusOut>', repopulate_defaults)
password_box.bind('<Return>', login)
password_box.grid(row=2, column=5, sticky='NS')


# adds login button and defines its properties
#B1 = Tkinter.Button(root, text ="FLAT", relief=FLAT )

login_btn = Button(root, text='Login', command=login, bg="light blue")
login_btn.bind('<Return>', login)
login_btn.grid(row=5, column=5, sticky='NS')

root.mainloop()

1 个答案:

答案 0 :(得分:0)

您不能将packgrid与共享相同父级或母版的小部件一起使用。 w1正在使用pack,但username_box正在使用grid