繁体   English   中英

点击 Tkinter 中的图像时如何调用 function?

[英]How to call a function when clicking on an image in Tkinter?

我知道使用command按钮很容易调用 function 按钮,但它与图像的工作方式不同。 我相信我的问题很简单,如何通过单击图像来调用 function?

这是代码。 我想点击picture ,这将调用make_newwindow function。

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=参数,该参数引用您希望在单击它时调用的 function。

这就是我的意思:

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()小部件方法将 function 附加到鼠标按钮 1 单击事件

为此,请更改上面的代码,使其创建Label (就像您的代码一样),但也如图所示调用bind() 请注意如何通过lambda表达式动态创建回调 function。 这是必需的,因为您的make_newwindow()不接受任何 arguments。 但是tkinter事件处理程序回调函数都传递了一个event参数(请参阅 事件和绑定)。 由于此处不需要,因此该参数被简单地忽略并命名为_ (此类事物的 Python 约定)。

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

这个怎么样? 这是有效的完整代码

import tkinter as tk
from tkinter import *


def make_newwindow(data):
    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="Capture001.png")
label0 = Label(root, image=picture, borderwidth=0, highlightthickness=0)
label0.place(x=62, y=205)


label0.pack()
label0.bind('<Button-1>', func=make_newwindow)


root.mainloop()

data是关于发生的事件的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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