Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - PhotoImage -- omitting option name

After seeing this, PhotoImage not showing up the image associated with it I wondered why omitting the type of option does not throws an error instead of just not showing up the image?

This code does not show the image without throwing any error

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

But this one works fine

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

On effbot it doesn't say anything about it so I checked tcl man page for creating photos but still can not find why it behaves like this.

Also, if those two are duplicate ones, let me know so I will delete/close vote this one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you specify a function with named arguments in python, those named arguments appear in a specific order. If you do not supply a name when defining these arguments, they are applied in the order that the arguments appear in the function definition.

In the case of PhotoImage, the first keyword argument is for the name of the image, not a path to a file. So, PhotoImage("ban.gif") is the same as doing PhotoImage(name="ban.gif"). It doesn't throw an error because "ban.gif" is a valid name, and there are use cases where you want to create an image without referencing a file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...