简体   繁体   中英

Python 2.7: tkinter, unable to add image to GUi

Python 2.7 Macbook OSX

I am trying to just add a image to my tkinter GUI, but am unable to. I am able to run the below script by itself and have an image on the GUI:

from Tkinter import *

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

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

root.mainloop()

But when i try to add the same lines:

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

My script seems to freeze, here is my script without the added lines, which runs fine:

#!/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()

You can't use both pack and grid together with widgets that share the same parent or master. w1 is using pack , but username_box is using grid .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM