我知道使用command
可以很容易地用Tkinter按钮调用一个函数,但是对于图像来说,它的工作方式并不相同。我认为我的问题很简单,如何单击图片即可调用函数?
这是代码。我要单击picture
,这将调用make_newwindow
函数。
from tkinter import *
import tkinter as tk
def make_newwindow():
global newwindow
root.withdraw()
newwindow = tk.Toplevel()
newwindow.title('Nível da grama região 2')
newwindow.geometry('580x520')
root = tk.Tk()
root.title('Nível da grama região 1')
root.geometry("580x520")
picture = PhotoImage(file="picture.png")
label0 = Label(root, image=picture, borderwidth=0, highlightthickness=0)
label0.place(x=62, y=205)
root.mainloop()
我认为,最简单的方法是将图像附加到Button
而不是Label
小部件,因为然后您需要做的就是指定一个command=
参数引用您想要的功能单击时将被调用。
这是我的意思:
import tkinter as tk
def make_newwindow():
global newwindow
raiz.withdraw()
newwindow = tk.Toplevel()
newwindow.title('Nível da grama região 2')
newwindow.geometry('580x520')
raiz = tk.Tk()
raiz.title('Nível da grama região 1')
raiz.geometry("580x520")
picture = tk.PhotoImage(file="picure.png")
btn0 = tk.Button(raiz, image=picture, borderwidth=0, highlightthickness=0,
command=make_newwindow)
btn0.place(x=62, y=205)
raiz.mainloop()
如果出于某些原因确实要使用Label
,则可以调用通用bind()
小部件方法以将功能附加到鼠标按钮1上,单击bind()
。
为此,请更改上面的代码,以便它创建一个events(就像您的代码一样),而且还如图所示调用Label
。注意如何通过bind()
表达式动态创建回调函数。这是必需的,因为您的lambda
不接受任何参数。但是,lambda
事件处理程序回调函数都传递了一个make_newwindow()
参数(请参见tkinter
)。由于这里不需要使用该参数,因此该参数将被简单地忽略,并被命名为event
(此类事物的Python约定)。
Events and Bindings
这个怎么样?这是有效的完整代码
_
...
picture = tk.PhotoImage(file="picure.png")
label0 = tk.Label(raiz, image=picture, borderwidth=0, highlightthickness=0)
label0.place(x=62, y=205)
label0.bind('<Button-1>', lambda *_: make_newwindow()) # Create and bind callback func.
raiz.mainloop()
是有关所发生偶数的信息