简体   繁体   中英

How to pass command to function from Tkinter Scale

I have a program with several sliders and need to run the same function for each of them but need to run based on which slider has been moved. How to I tell the function which slider was moved?

You do it like you do any other callback: use lambda or functools.partial to supply arguments.

For example:

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):

        tk.Frame.__init__(self, root)
        for scale in ("red", "green", "blue"):
            widget = tk.Scale(self, from_=0, to=255, orient="horizontal",
                              command=lambda value, name=scale: self.report_change(name, value))
            widget.pack()

    def report_change(self, name, value):
        print("%s changed to %s" % (name, value))


if __name__ == "__main__":
    root=tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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