Home > Enterprise >  Using Result of Tkinter Button Command to Another Tkinter Command Function
Using Result of Tkinter Button Command to Another Tkinter Command Function

Time:10-31

I have been struggling to complete the project I'm working on bc of this part. I want to use the result of a Button command function to another button command function whenever the user click the second button. Sample code attached below. The idea of this idiomatic script is that the first button is on coordinates calibration (actual space to computer screen space by calculating their respective ratios), and the second button will use the result of that calibration function to "convert" the coordinates that will be input for the second button. Just ignore the dummy operations I reflected here.

from tkinter import *
import tkinter as tk

root = Tk()


def solve1():
    x = [1, 2, 3]
    print(x)

def solve2():
    y = [4, 5, 6]
    print(y)

    z = x   y
    print(z)  # this is not working


Button1 = Button(root, text="Opt 1", command=solve1).grid(row=1, column=1, sticky="w")
Button2 = Button(root, text="Opt 2", command=solve2).grid(row=2, column=1, sticky="w")

root.mainloop()

Code is not working as python says solve1 is not defined. I'm new to the world of programming, so any shared thoughts is appreciated. PS: I need to extract a report of the results of these two functions, so I can't merge them into one function

CodePudding user response:

The easy, noobish way is to define the variable as global. For example (with some other best practice improvements):

import tkinter as tk

root = tk.Tk()

def solve1():
    global x
    x = [1, 2, 3]
    print(x)

def solve2():
    y = [4, 5, 6]
    print(y)

    z = x   y
    print(z)

Button1 = tk.Button(root, text="Opt 1", command=solve1)
Button1.grid(row=1, column=1, sticky="w")
Button2 = tk.Button(root, text="Opt 2", command=solve2)
Button2.grid(row=2, column=1, sticky="w")

root.mainloop()

The proper way is to make a class:

import tkinter as tk
    
class MSDS(tk.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        Button1 = tk.Button(self, text="Opt 1", command=self.solve1)
        Button1.grid(row=1, column=1, sticky="w")
        Button2 = tk.Button(self, text="Opt 2", command=self.solve2)
        Button2.grid(row=2, column=1, sticky="w")
    
    def solve1(self):
        self.x = [1, 2, 3]
        print(self.x)
    
    def solve2():
        y = [4, 5, 6]
        print(y)
    
        z = self.x   y
        print(z) 
    
def main():
    root = tk.Tk()
    win = MSDS(root)
    win.pack()
    root.mainloop()

if __name__ == "__main__":
    main()
  • Related