我是Python的新手,我可能过于复杂了。我没有使用类就可以工作,但我正在尽可能多地学习Python。我正在尝试从同一个类中的另一个函数中的一个函数访问变量。我的代码将在PyCharm控制台中显示各种项目,如何将这些项目放入我的GUI?这是我的整个代码:
# Python version 3.5.1
# pyVISA version 1.8
# Collect measurement data from an Agilent U2001A USB Power Sensor
from tkinter import * # tkinter is for setting up a GUI
from tkinter import ttk
import visa # Import the Python VISA module
class agilentU2001A(Frame):
def __init__(self, master): # Initialize the frame
Frame.__init__(self, master)
rm = visa.ResourceManager()
ports = rm.list_resources()
self.sensor = rm.open_resource(ports[0])
print(self.sensor)
self.grid()
self.sensorID()
self.createWidgets()
def createWidgets(self): # Create the labels and buttons
# Create connected instrument labels
self.label1 = Label(self, text="Connected sensor: ")
self.label1.grid(row=0, column=0, sticky=E)
self.instrumentLabel = Label(self, text="sensor_name")
self.instrumentLabel.grid(row=0, column=1, sticky=W)
# Create measurement labels
self.label2 = Label(self, text="Measurement: ")
self.label2.grid(row=1, column=0, sticky=E, pady=10)
self.measurementLabel = Label(self, text="numbers")
self.measurementLabel.grid(row=1, column=1, sticky=W, pady=10)
# Create measurement button
self.measureButton = ttk.Button(self, text="Take Measurement!", command=self.measurement)
self.measureButton.grid(row=2, column=1, pady=25)
# Create exit button
self.exitButton = ttk.Button(self, text="Exit", command=self.exit_measurement)
self.exitButton.grid(row=2, column=2, padx=25, pady=25)
def sensorID(self): # Get the ID from the connected sensor
self.sensor.write("*IDN?") # Query the instrument ID
sensor_init = self.sensor.read()
print("Sensor ID -> " + sensor_init)
def exit_measurement(self): # Close the VISA connection and program
self.sensor.close() # Close the connection
sys.exit()
def measurement(self): # Take a measurement
self.sensor.write("INIT:CONT ON") # Initiate the trigger to continuous on
self.sensor.write("FETC?") # Read data using the fetch command
measure = self.sensor.read()
print(measure)
root = Tk()
root.title("Agilent U2001A USB Power Sensor")
app = agilentU2001A(root)
w = 485 # set width of window
h = 180 # set height of window
ws = root.winfo_screenwidth() # get current screen width
hs = root.winfo_screenheight() # get current screen height
x = (ws / 2) - (w / 2) # calculate x coordinate for window
y = (hs / 2) - (h / 2) # calculate y coordinate for window
root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # center window on screen
root.mainloop() # Constantly checks for input