简体   繁体   English

对于 tkinter 中的多个 PanedWindow,如何在悬停时更改 PanedWindow 的颜色?

[英]how to change the color of PanedWindow upon hovering over it, for multiple PanedWindow in tkinter?

I am trying to make PanedWindow change color when I hover mouse over it in tkinter.当我在 hover 中将鼠标悬停在 tkinter 上时,我试图让 PanedWindow 改变颜色。

now this works for a single iteration.现在这适用于单次迭代。 but when i try to do it for multiple panedwindows it only changes color of the last window.但是当我尝试为多个窗格窗口执行此操作时,它只会更改最后一个 window 的颜色。

    import tkinter as tk

    root = tk.Tk()
    for i in range(10):

        m1 = tk.PanedWindow(root, bd=4, relief="flat", bg="blue")

        m1.pack()

        def on_enter(e):
             m1.config(background='OrangeRed3', relief="flat")


        def on_leave(e):
             m1.config(background='SystemButtonFace', relief="flat")


        # Create a Button
        button1 = tk.Button(m1, text=f"{i}")
        button1.pack(pady=20)

        # Bind the Enter and Leave Events to the Button
        m1.bind('<Enter>', on_enter)
        m1.bind('<Leave>', on_leave)

        m1.add(button1)
    tk.mainloop()

Since at each iteration of the loop all variables are overwritten , the functions are bound to the last created element.由于在循环的每次迭代中,所有变量都被覆盖,函数被绑定到最后创建的元素。 It is necessary to pass the desired element to the function. It is even better to collect everything created in dictionaries, so that in the future you can easily change them.有必要将所需的元素传递给 function。最好将在字典中创建的所有内容收集起来,以便将来您可以轻松更改它们。

import tkinter as tk
from functools import partial

ms = {}
btns = {}

root = tk.Tk()


def on_enter(m, e):
    m.config(background='OrangeRed3', relief="flat")


def on_leave(m, e):
    m.config(background='SystemButtonFace', relief="flat")

for i in range(10):

    ms[i] = tk.PanedWindow(root, bd=4, relief="flat", bg="blue")
    ms[i].pack()

    # Create a Button
    btns[i] = tk.Button(ms[i], text=f"{i}")
    btns[i].pack(pady=20)

    # Bind the Enter and Leave Events to the Button
    ms[i].bind('<Enter>', partial(on_enter, ms[i]))
    ms[i].bind('<Leave>', partial(on_leave, ms[i]))

    ms[i].add(btns[i])
tk.mainloop()

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

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