【问题标题】:Python 2.7: tkinter, unable to add image to GUiPython 2.7:tkinter,无法将图像添加到 GUI
【发布时间】:2018-05-21 17:58:23
【问题描述】:

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

【问题讨论】:

  • 我假设您的实际代码中有一个括号?
  • 是的,我在上面修复了它

标签: python macos tkinter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2015-01-18
    • 2017-12-04
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2013-01-28
    相关资源
    最近更新 更多