Using imported functions as tkinter callbacks

41 views Asked by At

I’m trying to write some Python code to control a couple of instruments using pyvisa. I’m new to Python, so please bear with me. I have some code that works, but I’m really struggling to figure out how to interface this with a tkinter-based GUI.

For my working code, I have a main file (Main.py) which has the main code, and two modules (powermeter.py and powersupply.py) which contain functions for interfacing to the two instruments. This works fine. Some example code is shown here, I’ve only shown code related to one instrument (powersupply) for simplicity. One function (again, just showing one for simplicity) connect() from the module powersupply.py is:

def connect(resource_manager, ID):
    """Open a connection to the supply"""
    instrument_name = resource_manager.open_resource(ID)
    return instrument_name

The main program searches the list of available VISA instruments for a VISA ID that matches what I expect from the brand/model of meter we use. This is saved to the variable ThorID.

import pyvisa
import powermeter

rm = pyvisa.ResourceManager()  # Set up resource manager
resource_list = rm.list_resources()  # Create a list of available instruments

""" Establish connection to power meter """
Thor_str = "0x1313::0x8079"  # Power meter ID should contain this string
Thor = [i for i, s in enumerate(resource_list) if Thor_str in s]

if len(Thor) == 0:
    print("No Thor Labs power meter detected")
    ThorID = ""
else:
   ThorID = resource_list[Thor[0]]  # This is the Thor Labs VISA ID
   print("Thor Labs power meter detected")

I can then use the function connect() to connect to the meter once it has been found and then return the variable pm, which is (as I understand) the full VISA resource name/ID that I need for other functions (not shown here):

pm = powermeter.connect(rm, ThorID)  # Open a connection to the Power Meter

So far so good. However, my understanding totally breaks down when considering how to integrate this to a GUI. In the GUI there is a button (tk.Button) Connect to device. When I push this button, essentially I want to execute the command pm = powermeter.connect(rm, ThorID), making a connection and returning the variable pm. However tkinter wants me to use the syntax command = function_name(), and I know that the syntax command = pm = powermeter.connect(rm, ThorID) can’t be right!

I’ve tried defining another function in the main program, called e.g. connect_instruments(). However, that also appears to be the wrong way to do it because it seems to execute even before I press the button!

If anyone could give some advice here, that would be great. I find this incredibly confusing to be honest, even though what I want to do (execute this code when this button is pressed) seems very simple!

0

There are 0 answers