I want to select multiple devices and the udid will change too. And one more thing I want to have multiple also url http://localhost in range(4700, 4790)

from tkinter import Tk, Label, Entry, Button, Listbox, END
from tkinter.font import Font
from appium import webdriver
from typing import Any, Dict
from appium.options.common import AppiumOptions
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import subprocess
import re

# Define the package names and their corresponding numbers
package_numbers = {
    1: 'com.facebook.katanb',
    2: 'com.facebook.katanc',
    3: 'com.facebook.katand',
    4: 'com.facebook.katane',
    5: 'com.facebook.katanf',
    # Add more package names and numbers here
}

cap: Dict[str, Any] = {
    "platformName": 'Android',
    "platformVersion": '9',
    "deviceName": 'Sam',
    "udid": '192.168.132.63:5555',
    "automationName": 'UiAutomator2',
}

url = 'http://localhost:4723'

def get_connected_devices():
    result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
    output = result.stdout.strip().split('\n')
    devices = [line.split('\t')[0] for line in output[1:] if 'device' in line and 'offline' not in line]
    connected_devices = []
    for device in devices:
        facebook_apps_count = check_facebook_apps_for_device(device)
        connected_devices.append({'device_id': device, 'facebook_apps_count': facebook_apps_count})
    return connected_devices

def check_facebook_apps_for_device(device_id: str) -> int:
    result = subprocess.run(['adb', '-s', device_id, 'shell', 'pm', 'list', 'packages'], capture_output=True, text=True)
    output = result.stdout.strip()
    packages = re.findall(r'package:(.*)', output)
    facebook_apps = [package for package in packages if package.startswith('com.facebook')]
    return len(facebook_apps)

def run_sequence():
    start_number = int(start_entry.get())
    end_number = int(end_entry.get())

    # Get the selected device from the device_listbox
    selected_device_index = device_listbox.curselection()
    if selected_device_index:
        selected_device = device_listbox.get(selected_device_index)
        cap["udid"] = selected_device.split(' ')[0]

    driver = webdriver.Remote(url, options=AppiumOptions().load_capabilities(cap))

    # Clear the listbox
    process_listbox.delete(0, "end")

    # Display the list of package names
    for number in range(start_number, end_number + 1):
        package_name = package_numbers[number]
        process_listbox.insert("end", package_name)
        process_listbox.itemconfig(number - start_number, {'bg': 'white'})

    # Wait for a moment before starting the script execution
    status_label.config(text="Waiting...")
    window.update()  # Update the window to display the waiting status
    time.sleep(3)  # Adjust the delay duration as needed

    # Run the sequence of actions within the specified range of package numbers
    for number in range(start_number, end_number + 1):
        package_name = package_numbers[number]
        status_label.config(text=f"Processing {package_name}...")
        process_listbox.itemconfig(number - start_number, {'bg': 'white'})

        driver.activate_app(package_name)
        time.sleep(3)

        # Perform the desired actions for each app
        try:
            el1 = driver.find_element(by=AppiumBy.XPATH,
                                      value="//android.widget.Button[@content-desc=\"Create, Double tap to create a new post, story, or reel\"]/android.widget.FrameLayout/android.view.View")
            el1.click()

            # Replace time.sleep(2) with an explicit wait
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((AppiumBy.ID, "element_id")))

            # Add a delay to simulate processingtime
            time.sleep(5)
            status_label.config(text=f"{package_name} done.")
            process_listbox.itemconfig(number - start_number, {'bg': 'green'})
            window.update()  # Update the window to immediately display the change

            # Wait for a moment before processing the next app
            if number < end_number:
                time.sleep(1)  # Adjust the delay duration as needed
        except NoSuchElementException:
            # Close the app
            time.sleep(3)
            driver.press_keycode(187)
            time.sleep(1)
            el18 = driver.find_element(by=AppiumBy.ID, value="com.android.systemui:id/button")
            el18.click()
            time.sleep(3)

def get_installed_packages(device_id: str):
    result = subprocess.run(['adb', '-s', device_id, 'shell', 'pm', 'list', 'packages'], capture_output=True, text=True)
    output = result.stdout.strip()
    packages = re.findall(r'package:(.*)', output)
    return packages

# Create the main window
window = Tk()
window.title("App Sequence")
window.geometry("800x600")  # Increase the window size

# Create a custom font for labels
label_font = Font(family="Helvetica", size=14, weight="bold")  # Increase the font size

# Create labels, entries, and listboxes
start_label = Label(window, text="Start Number:", font=label_font)
start_label.pack()
start_entry = Entry(window)
start_entry.pack()

end_label = Label(window, text="End Number:", font=label_font)
end_label.pack()
end_entry = Entry(window)
end_entry.pack()

device_label = Label(window, text="Connected Devices:", font=label_font)
device_label.pack()
device_listbox = Listbox(window, selectmode="single", width=100, height=5)  # Increase the height
device_listbox.pack()

process_label = Label(window, text="Process List:", font=label_font)
process_label.pack()
process_listbox = Listbox(window, selectbackground="lightgray",width=100, height=10)  # Increase the height
process_listbox.pack()

status_label = Label(window, text="", font=label_font)
status_label.pack()

# Get the list of connected devices and populate the device_listbox
devices = get_connected_devices()
for device in devices:
    device_id = device['device_id']
    facebook_apps_count = device['facebook_apps_count']
    device_listbox.insert(END, f"{device_id} (Facebook Apps: {facebook_apps_count})")

# Create a button to run the sequence
run_button = Button(window, text="Run Sequence", command=run_sequence)
run_button.pack()

# Start the main loop
window.mainloop()