【问题标题】:PhotoImage -- omitting option namePhotoImage -- 省略选项名称
【发布时间】:2015-01-18 11:10:34
【问题描述】:

看到这里,PhotoImage not showing up the image associated with it我想知道为什么省略选项类型不会引发错误,而不是不显示图像?

此代码不显示图像而不会引发任何错误

import tkinter as tk
root = tk.Tk()

image1 = tk.PhotoImage("ban.gif")
tk.Label(root,image=image1).pack()
tk.Label(root, text="some string here").pack()

root.mainloop()

但是这个很好用

import tkinter as tk
root = tk.Tk()

image1 = tk.PhotoImage(file="ban.gif")
tk.Label(root,image=image1).pack()
tk.Label(root, text="some string here").pack()

root.mainloop()

在 effbot 上它没有说明任何内容,所以我检查了 tcl 手册页中的 creating photos,但仍然找不到它为什么会这样。

另外,如果这两个是重复的,请告诉我,以便我删除/关闭投票。

【问题讨论】:

  • “创建照片”的链接与您的问题无关——该链接指向如何将图像添加到画布。

标签: python tkinter


【解决方案1】:

当你在 python 中指定一个带有命名参数的函数时,这些命名参数以特定的顺序出现。如果在定义这些参数时不提供名称,它们将按照参数出现在函数定义中的顺序应用。

在 PhotoImage 的情况下,第一个关键字参数是图像的 名称,而不是文件的路径。所以,PhotoImage("ban.gif")PhotoImage(name="ban.gif") 是一样的。它不会引发错误,因为“ban.gif”是一个有效名称,并且在某些用例中,您希望在不引用文件的情况下创建图像。

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 2017-10-28
    • 2020-01-19
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多