William Scantlin
William Scantlin

Reputation: 123

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?

Upvotes: 1

Views: 3471

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386220

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

Upvotes: 1

Related Questions