Mar-22-2023, 02:59 AM
How do I define the selected port as global so I can call it anywhere in my code.
In below code I have selecting the serial port inside a function.SO I cannot use it anywhere in my code.
How can I make it as global?
In below code I have selecting the serial port inside a function.SO I cannot use it anywhere in my code.
How can I make it as global?
import tkinter as tk
import tkinter.ttk as ttk
import serial.tools.list_ports
import serial
import time
# --- main ---
root = tk.Tk()
#This is our label
label = ttk.Label(root, text = "Please Select a COM PORT")
label.grid(column = 1, row = 4)
label.pack()
#Functions
def on_select(event=None):
# get selection from event
print("event.widget:", event.widget.get())
# or get selection directly from combobox
print("comboboxes: ", cb.get())
val = cb.get()
label.configure(text= val[:5])
selected_COM = val[:5]
#====================
# create a serial object
selected_COM = val[:5]
ser = serial.Serial(selected_COM) # replace 'COM1' with the name of your serial port
ser.baudrate = 9600
ser.bytesize=8
ser.parity ='N' # No parity
ser.stopbits = 1 # Number of Stop bits = 1
time.sleep(3)
#ser.write(b"A") #transmit 'A' (8bit) to micro/Arduino
#ser.close() # Close the port
#=====================
cb = ttk.Combobox(root, values=serial_ports())
cb.pack()
label2 = ttk.Label(root, text = "Please Insert a Number")
label2.pack()
# assign function to combobox
cb.bind('<<ComboboxSelected>>', on_select)
