error generated in the below code snippet
def create_checkbox_list(self):
# Create a frame for the checkbox list
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
code
# Checkbox for secure option
self.all_app = tk.BooleanVar() # This should be an instance variable
checkbox_ = tk.Checkbutton(self.checkbox_frame, text="All",
variable=self.all_app, command=self.enable_full_execution_test)
checkbox_.pack(pady=10)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = i // 4
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
File "D:\ARTSpa\LAVU\IT_Lavu\integrationtestlavu\ui.py", line 242, in create_checkbox_list
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
File "C:\python311\Lib\tkinter_init_.py", line 2549, in grid_configure
self.tk.call(
_tkinter.TclError: cannot use geometry manager grid inside .!frame3 which already has slaves managed by pack
Assistant
The error message you're encountering indicates that you're trying to mix two different geometry managers—pack and grid—in the same parent widget (in this case, self.checkbox_frame). In Tkinter, you can only use one geometry manager (either pack or grid) for the same parent widget.
Here’s how you can resolve the error:
Choose a single geometry manager: Decide if you want to layout your widgets using pack or grid. If you prefer to use grid, you should replace pack calls with grid in your code.
Update the layout accordingly: If you decide to go with grid, make sure to replace all instances of pack in self.checkbox_frame with appropriate grid calls so that all children of this frame use the same geometry manager.
Based on your initial code, here's a version that uses only grid throughout:
python
User
checkbox for all is not in the screen.. I need to integrate with the current list of checkbox with "all"
Assistant
If you want your "All" checkbox to be integrated into the same list of checkboxes, you can simply adjust the grid layout to accommodate it in the existing structure. You might want to place it in a specific position, such as the first cell of the grid, or have it span multiple columns.
Here’s an updated version of your previous code that includes the "All" checkbox as part of the grid layout, right at the top, integrated with the other checkboxes:
python
import tkinter as tk
class YourClass:
def __init__(self, root):
self.root = root
self.checkbox_names = [
"Option 1", "Option 2", "Option 3", "Option 4",
"Option 5", "Option 6", "Option 7", "Option 8"
]
self.check_vars = [tk.BooleanVar() for _ in self.checkbox_names] # Create BooleanVars for each checkbox
self.create_checkbox_list()
def create_checkbox_list(self):
# Create a frame for the checkbox list
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.grid(pady=20) # Use grid for the frame
# Checkbox for "All" option
self.all_app = tk.BooleanVar() # This should be an instance variable
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5) # Span across 4 columns
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1 # Start from row 1 because row 0 is for the "All" checkbox
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def enable_full_execution_test(self):
# Implement functionality for "All" checkbox here
if self.all_app.get():
# Check all checkboxes when "All" is turned on
for var in self.check_vars:
var.set(True)
else:
# Optionally uncheck all checkboxes if "All" is turned off
for var in self.check_vars:
var.set(False)
def checkbox_toggled(self, index):
# Implement functionality when individual checkboxes are toggled here
pass
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = YourClass(root)
root.mainloop()
User
this is my UI code so we need to create a seperate thread for the UI .. because it takes lot of time to execute ..
ui.py
import os
import threading
import tkinter as tk
from plyer import notification
import pygame
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager
To make your Tkinter UI responsive during a long-running operation, you can use threading. You have already initiated a separate thread for the IntegrationTestManager in your initTestManager method. However, it looks like you might want the UI to stay responsive and allow user interactions while integration tests are running. Below, I'll clarify how you can structure the code to better integrate threading for long-running tests and ensure the UI remains responsive.
Updated Code Snippet
Here's how you can enhance your existing code with proper threading:
Run Long-Running Tasks in a Thread: You are already doing this by starting the IntegrationTestManager in a separate thread.
Use queue.Queue: To communicate between the worker thread and the UI thread, especially for updating the UI based on the thread's completion or status updates, use Python's queue library.
Update the UI: Use the after() method of the Tkinter root window to periodically check for results or status updates from the worker thread.
Below is the updated code for your LaveUi class that incorporates these ideas:
python
User
and handle those thread smoothly when exit
Assistant
Handling threads smoothly when exiting a Tkinter application is crucial to prevent potential issues such as memory leaks, locked resources, or unresponsive UI. Below, I will demonstrate how to manage the thread associated with the IntegrationTestManager cleanly and ensure the application exits gracefully.
Key Steps to Handle Threading on Exit
Flag for Termination: Introduce a flag that tells the worker thread to stop its operations when the application exits.
Join the Thread: Ensure the main thread waits for the worker thread to finish before quitting the UI.
Clean Up: Close or clean up any resources that the worker thread might be using.
Here’s how you can implement these aspects in your code. I've added a mechanism to set a termination flag and to cleanly join the thread during exit:
Updated Code for Graceful Exit Handling
python
User
full source code
Assistant
Certainly! Below is the complete source code for your Tkinter application using threading for long-running operations. It includes all the necessary components, such as the user interface, threading management, and proper cleanup on exit.
python
User
its not my full source code and i need a UI thread handle the UI update also
Assistant
I apologize for the oversight! Let's integrate all the necessary elements—including the animation, UI handling, and threading—into a complete example that properly manages UI updates and handles long-running tasks in the background. Here’s the complete code with comments included and improvements for UI responsiveness and updates.
Complete Source Code
python
User
where is the Labels and Entry for Software Version
Assistant
My apologies for missing the "Software Version" label and entry in the previous complete code example! Here's the updated version of the code, which now correctly includes the entry for the Software Version.
Complete Source Code with Software Version Entry
python
User
alpha for the boot animation is not work
Assistant
If the alpha (transparency) for the boot animation isn't working as expected, there are a few potential reasons, as it may relate to how the images are processed and displayed in Tkinter.
Here are some common points to check:
Transparency Handling: The handling of transparency in images may need to be adjusted. When you manipulate pixel data (like changing a certain color to be transparent), ensure the pixel format supports an alpha channel (RGBA).
Image Format: Ensure that the images you're using support transparency in formats such as PNG. If you're using a format like JPG, it won't support transparency.
Image Resizing: When resizing images, make sure you're keeping the alpha channel intact.
Here’s an enhanced version of the load_animation_images method to ensure transparency is handled correctly, along with a complete code context for clarity:
Updated load_animation_images Method
The following method correctly retains transparency while loading images:
python
def load_animation_images(self):
""" Load animation images from a directory. """
directory = "boot_images" # Directory containing boot images
for i in range(1, 30): # Assuming you have images named 1.png to 29.png
img_path = os.path.join(directory, f'{i}.png')
# Open the image
img = Image.open(img_path)
# Ensure the image has an alpha channel
img = img.convert("RGBA") # Convert to RGBA format
datas = img.getdata() # Get the pixel data
new_data = []
for item in datas:
# Modify this part to set the specific background color you want to remove
# For example, remove white background (255, 255, 255)
if item[0] > 240 and item[1] > 240 and item[2] > 240: # Check for near-white colors
new_data.append((255, 255, 255, 0)) # Change to transparent
else:
new_data.append(item)
img.putdata(new_data) # Update the image data
img = img.resize((100, 50), Image.LANCZOS) # Resize for display
self.images.append(ImageTk.PhotoImage(img)) # Store the PhotoImage in the list
User
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
self.ip_address = self.ip_address.get()
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = self.software_ver.get()
self.initTestManager()
getting error like File "D:\ARTSpa\LAVU\IT_Lavu\integrationtestlavu\ui.py", line 235, in get_user_input
print("IP Address:", self.ip_address.get())
^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
server_ip=self.ip_address.get(), grpc_port=self.grpc_port,
^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
User input:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\python311\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\python311\Lib\tkinter_init_.py", line 861, in callit
func(*args)
File "D:\ARTSpa\LAVU\IT_Lavu\integrationtestlavu\ui.py", line 135, in check_init_complete
self.stop_boot_animation() # Stop the animation when initialization is complete
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\ARTSpa\LAVU\IT_Lavu\integrationtestlavu\ui.py", line 142, in stop_boot_animation
self.create_checkbox_list() # Create checkbox list after boot animation
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\ARTSpa\LAVU\IT_Lavu\integrationtestlavu\ui.py", line 252, in create_checkbox_list
command=self.enable_full_execution_test
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'LaveUi' object has no attribute 'enable_full_execution_test'
Assistant
The errors you're encountering appear to be due to a couple of issues in your get_user_input method and potential method definitions in your class. Let's address these issues step by step.
Fixing the Errors
Updating Variable Assignments:
In your method get_user_input, you're attempting to call get() on self.ip_address, self.dlt_port, self.grpc_port, and self.software_ver after you have assigned values to them as strings. This overwriting means that you cannot call get() on a string. You need to retrieve their values before you overwrite them.
Missing Method Definition:
You seem to be calling a method self.enable_full_execution_test that isn’t defined in your class. You either need to create this method or remove the command reference from the checkbox if you don't require it.
Revised get_user_input Method
Here's how you could correct the get_user_input method:
python
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
# Get user inputs
ip_address = self.ip_address.get() # Correctly getting the value
dlt_port = self.dlt_port.get() # Get value directly
grpc_port = self.grpc_port.get() # Get value directly
software_ver = self.software_ver.get() # Get value directly
# Print user input for debugging
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
self.initTestManager() # Start the test manager with the gathered values
User
Exception: Failed to connect to DLT server at 10.0.10.154:.!frame2.!entry2 - 'Entry' object cannot be interpreted as an integer
Assistant
The error message you're encountering indicates that there's an issue with how you're trying to connect to a DLT server. Specifically, the message suggests that an Entry widget (likely your DLT port input) is being interpreted incorrectly, likely because you're trying to use it where an integer is expected.
In your code, you seem to be using the DLT port entry directly when initializing your IntegrationTestManager, but you might not be converting it to an integer. Here’s how to fix this:
1. Ensure DLT Port is an Integer
In the get_user_input() method, when you get the DLT port from the Entry field, you need to convert it to an integer. Here’s the modified code:
python
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
# Get user inputs
ip_address = self.ip_address.get() # Get the IP address
dlt_port = int(self.dlt_port.get()) # Convert DLT port to an integer
grpc_port = self.grpc_port.get() # Get gRPC port as string (if it can be an int convert similarly)
software_ver = self.software_ver.get() # Get software version as string
# Print user input for debugging
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
# Start the test manager with the gathered values
self.initTestManager(ip_address, dlt_port, grpc_port, software_ver) # Pass the right parameters if needed
2. Adjust Your initTestManager Method
User
def init(self, d_can_dbc_file_path: str, p_can_dbc_file_path: str,
server_ip="10.0.8.225", grpc_port="8866", dlt_port=3490, secure=False, cycle_id=""):
this the IntegrationTestManager class
Assistant
Given the signature of the IntegrationTestManager class constructor that you've provided, it looks like it takes various input parameters, including paths to DBC files, server configurations, and a secure boolean.
Key Observations:
Parameter Types: You should ensure that when you pass values from your UI (like the IP address and DLT port), they match what the IntegrationTestManager expects, both in type and validity.
IP Address: server_ip should be a string, which is fine since we are retrieving it from an Entry widget.
gRPC Port: Ensure this is passed as a string as the signature suggests.
DLT Port: This needs to be an integer.
Complete Example of Integration with IntegrationTestManager
Here is how to properly integrate the get_user_input function from your UI class and create an instance of the IntegrationTestManager:
python
User
full source code
Assistant
Certainly! Below is the full source code for your LaveUi Tkinter application, integrated with the handling for the IntegrationTestManager. The code includes all the necessary methods, proper user input handling, and error checking. It also ensures that DLT port input is converted to an integer and parameters are passed correctly.
inside the IntegrationTestManager .. so we need to check the varible set as true and call check_init_complete
Assistant
To implement a mechanism that checks the init_event variable to determine when the IntegrationTestManager initialization is complete, you can follow these steps:
Modify the IntegrationTestManager Class: Ensure that the init_event variable is being utilized correctly when initialization is complete.
Check the Status Periodically: In the LaveUi class, continuously check the status of the init_event variable to determine when to proceed.
Here’s how to structure this:
Modified IntegrationTestManager
In your IntegrationTestManager class, ensure you set self.init_event to True when the initialization completes:
import tkinter as tk
class YourClass:
def __init__(self, root):
self.root = root
self.checkbox_names = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6", "Option 7", "Option 8"]
self.check_vars = [tk.BooleanVar() for _ in self.checkbox_names] # Assuming you have a list of check variable
self.create_checkbox_list()
def create_checkbox_list(self):
# Create a frame for the checkbox list
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.grid(pady=20) # Use grid instead of pack
# Checkbox for secure option
self.all_app = tk.BooleanVar() # This should be an instance variable
checkbox_ = tk.Checkbutton(
self.checkbox_frame, text="All",
variable=self.all_app, command=self.enable_full_execution_test
)
checkbox_.grid(row=0, column=0, sticky='w', padx=10, pady=5) # Use grid for this checkbox
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1 # Start from row 1 because row 0 is used for the "All" checkbox
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def enable_full_execution_test(self):
# Implement your functionality here
pass
def checkbox_toggled(self, index):
# Implement your functionality here
pass
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = YourClass(root)
root.mainloop()
In this version:
I've replaced the call to pack() with grid().
Adjusted the row assignments in the loop so the checkboxes start at row 1, allowing row 0 for the "All" checkbox.
Keep the sticky, padx, and pady options as they were to maintain layout spacing.
Now the code should run without mixing geometry managers and causing errors.
Changes Made:
All Checkbox Position:
The "All" checkbox is set to occupy the first row (row=0) and spans across all four columns using columnspan=4. This makes it more visually integrated with the checkboxes that follow it.
Checkbox Retaining Functionality:
The method enable_full_execution_test is modified so that when the "All" checkbox is checked, all other checkboxes will be checked as well. You can customize this behavior depending on your requirements.
Layout Consistency:
All checkboxes, including the "All" checkbox, are managed using the grid geometry manager, ensuring no geometry manager conflicts occur.
This way, your "All" checkbox is integrated seamlessly into the interface, maintaining a clear and organized layout.
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord",
"SD13_DeleteDashCamRecord", "SD15_SetAndUnsetDashCamRecordToFavourite",
"SD21_MemoriesRecordingSaving", "SD21_MemoriesRecordingDiscarding",
"SD22_MemoriesPlayback", "SD24_ExportMemories", "SD25_SetMemoriesToFavourite",
"SD23_DeleteMemories", "SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest", "SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Animation variables
self.images = []
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
self.exit_frame = tk.Frame(self.root) # Create a frame for buttons
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
self.get_ui_input()
def exit_button(self):
# Button to exit the application
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10) # Position at the bottom
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 30): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'{i}.png')
img = Image.open(img_path)
# Optional: Process the image to remove a specific background color or make it transparent
img = img.convert("RGBA") # Ensure image has alpha channel
datas = img.getdata()
new_data = []
for item in datas:
# Modify this part to set the specific background color you want to remove
# For example, remove white background
if item[0] in list(range(200, 256)) and item[1] in list(range(200, 256)) and item[2] in list(
range(200, 256)):
# Change all white (also shades of white) to transparent
new_data.append((255, 255, 255, 0)) # Change to transparent
else:
new_data.append(item)
img.putdata(new_data)
img = img.resize((100, 50), Image.LANCZOS) # Use Image.LANCZOS for high-quality downsampling
self.images.append(ImageTk.PhotoImage(img))
def start_boot_animation(self):
self.update_animation()
self.root.after(100) # Start after a short delay
def update_animation(self):
if self.animation_running:
# Update the image shown in the label
self.animation_label.config(image=self.images[self.image_index])
self.image_index = (self.image_index + 1) % len(self.images)
self.root.after(100, self.update_animation) # Change image every 100ms
def stop_boot_animation(self):
self.animation_running = False
self.animation_label.config(image='') # Clear the label when stopping
self.loading_label.config(text='')
self.create_checkbox_list()
def get_ui_input(self):
# Main frame for the input fields
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# Top frame for the first two inputs
top_frame = tk.Frame(input_frame)
top_frame.grid(row=0, column=0)
# Labels and Entry for IP Address
self.user_input_ip_label = tk.Label(top_frame, text="IP Address")
self.user_input_ip_label.grid(row=0, column=0, padx=10, pady=10)
self.ip_address = tk.Entry(top_frame, font=("Helvetica", 16))
self.ip_address.grid(row=1, column=0, padx=10, pady=10)
# Labels and Entry for DLT Port
self.user_input_dlt_label = tk.Label(top_frame, text="DLT Port")
self.user_input_dlt_label.grid(row=0, column=1, padx=10, pady=10)
self.dlt_port = tk.Entry(top_frame, font=("Helvetica", 16))
self.dlt_port.grid(row=1, column=1, padx=10, pady=10)
# Bottom frame for the next two inputs
bottom_frame = tk.Frame(input_frame)
bottom_frame.grid(row=1, column=0)
# Labels and Entry for gRPC Port
self.user_input_grpc_label = tk.Label(bottom_frame, text="gRPC Port")
self.user_input_grpc_label.grid(row=0, column=0, padx=10, pady=10)
self.grpc_port = tk.Entry(bottom_frame, font=("Helvetica", 16))
self.grpc_port.grid(row=1, column=0, padx=10, pady=10)
# Labels and Entry for Software Version
self.user_input_software_label = tk.Label(bottom_frame, text="Software Version")
self.user_input_software_label.grid(row=0, column=1, padx=10, pady=10)
self.software_ver = tk.Entry(bottom_frame, font=("Helvetica", 16))
self.software_ver.grid(row=1, column=1, padx=10, pady=10)
# Checkbox for secure option
self.var = tk.BooleanVar() # This should be an instance variable
checkbox = tk.Checkbutton(self.root, text="Secure", variable=self.var, command=self.secure_selection)
checkbox.pack(pady=10)
# Submit button
self.submit_button = tk.Button(self.root, text="Submit", command=self.get_user_input)
self.submit_button.pack(pady=10)
def secure_selection(self):
if self.var.get():
self.secure = True
else:
self.secure = False
def get_user_input(self):
if self.app_set_state:
# Get text from the Entry widgets
ip_address = self.ip_address.get()
dlt_port = self.dlt_port.get()
grpc_port = self.grpc_port.get()
software_ver = self.software_ver.get()
self.loading_label.config(text="Application Initialization in Progress !!")
self.initTestManager()
self.app_set_state = False
# Print the values to debug or process them later
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Start..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
def enable_full_execution_test(self):
if self.all_app.get():
self.enable_full_execution = True
else:
self.enable_full_execution = False
def create_checkbox_list(self):
# Create a frame for the checkbox list
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# Checkbox for "All" option
self.all_app = tk.BooleanVar() # This should be an instance variable
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) +1
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def checkbox_toggled(self, index):
# Get the boolean value of the corresponding checkbox
if self.check_vars[index].get(): # If checkbox is checked
method_name = self.checkbox_names[index] # Get the method name from the list
if self.test_handler.init_event:
method = getattr(self.test_handler, method_name, None) # Fetch the method
if method: # Check if the method exists
method() # Call the method
else:
self.show_toast()
print(f"Method {method_name} is not defined in IntegrationTestManager.")
else:
print(f"Test Application Init In Complete..")
def run_integration_test_manager(self):
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port="8866",
dlt_port=3490, secure=self.secure)
def initTestManager(self):
self.init_event = threading.Event()
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
# self.init_event.wait()
# Monitor the integration manager thread
self.root.after(100, self.check_init_complete) # Check every 100ms
def check_init_complete(self):
if self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the boot animation
def deinitTestManager(self):
print(f"deinitTestManager ....Start")
# Stop the DLT log receiver thread
self.test_handler.dlt_manager.stop_dlt_thread()
# print("Adding Result on Excel file.")
# report_manager.insert_value_report_excel(test_handler.list_tests)
self.test_handler.save_report_excel()
# can_manager.stop_key()
# can_manager.stop_can()
self.test_handler.finish_can_manager()
self.test_handler.FinishGrpcConnection()
self.thread.join() # Wait for the thread to finish
print(f"deinitTestManager ....END")
def exit_ui_application(self):
print(f"UI Application Exit !!")
self.deinitTestManager()
self.root.quit()
import os
import threading
import tkinter as tk
from plyer import notification
import pygame
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager
import queue
class LaveUi:
def __init__(self, root):
self.enable_full_execution = False
self.all_app = None
self.var = None
self.user_input_grpc_label = None
self.user_input_dlt_label = None
self.user_input_ip_label = None
self.user_input_software_label = None
self.secure = False
self.submit_button = None
self.app_set_state = True
self.user_input = None
self.user_input_label = None
self.animation_thread = None
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.init_mngr_status = False
self.thread = None
self.queue = queue.Queue() # Queue for UI updates
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
# Add your checkbox names here...
]
# Animation variables
self.images = []
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
self.exit_frame = tk.Frame(self.root) # Create a frame for exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
self.get_ui_input()
# Start a periodic check for updates
self.check_queue()
# ... Other existing methods remain unchanged ...
def initTestManager(self):
self.init_event = threading.Event()
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self):
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port="8866",
dlt_port=3490, secure=self.secure
)
# After the initialization (if needed), you can add code to update the queue
# self.queue.put("Initialization complete") # Example message
def check_init_complete(self):
if self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the boot animation
self.queue.put("Initialization complete") # Put a message in the queue
def check_queue(self):
try:
while True: # Process all messages in the queue
message = self.queue.get_nowait()
self.loading_label.config(text=message) # Update the loading label
# You can insert other UI updates here if necessary
except queue.Empty:
pass # No messages in the queue
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Exit application method after deinitializing the test manager
def exit_ui_application(self):
print("UI Application Exit !!")
self.deinitTestManager()
self.root.quit()
# The rest of your methods remain unchanged...
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Key Changes:
Queue for Updates:
A queue.Queue instance named self.queue is added to manage communication between the worker thread and the UI thread.
Check Queue Periodically:
The check_queue method is introduced to look for messages in the queue, updating the UI as necessary. This keeps your UI responsive without blocking.
Thread Communication:
When the initialization of the IntegrationTestManager is complete, a message can be put in the queue to indicate that the process is finished.
Commented Sections:
Ensure to add your checkbox names and fill other parts as required.
With these changes, your UI will remain responsive, and the integration test manager can run in the background efficiently.
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager
import queue
class LaveUi:
def __init__(self, root):
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.submit_button = None
self.app_set_state = True
self.animation_label = tk.Label(self.root)
self.root = root
self.test_handler = None
self.init_event = None
self.queue = queue.Queue() # Queue for UI updates
self.thread = None
self.terminate_thread = False # Flag for thread termination
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Integrate additional UI elements as needed...
self.exit_frame = tk.Frame(self.root) # Create a frame for exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
self.check_init_complete()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self):
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
# Start checking for completion, adjust as needed
self.root.after(100, self.check_init_complete)
def run_integration_test_manager(self):
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip="your_ip", grpc_port="8866", dlt_port=3490, secure=self.secure)
# Here you would typically run your integration tests
while not self.terminate_thread:
# Simulate long running task
# Check for any exiting conditions
if not self.terminate_thread:
# Perform some task; replace with actual logic
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
if self.thread and self.thread.is_alive():
# Check the thread's status
self.root.after(100, self.check_init_complete)
else:
self.stop_boot_animation() # Hook into your UI logic as needed
# Implement other methods as needed...
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Key Changes Explained
Termination Flag:
The boolean self.terminate_thread is introduced to signal the worker thread to stop processing.
Graceful Exit:
In the exit_ui_application method, we check if the thread is alive. If it is, the flag is set, and we call join() to wait for it to terminate. A timeout is specified to prevent the main thread from waiting indefinitely.
Worker Thread Loop:
In the run_integration_test_manager method, the while loop now checks the self.terminate_thread variable. When it is set to True, the loop will exit, allowing the thread to finish cleanly.
UI Responsiveness:
The UI remains responsive throughout execution, and the check_init_complete() method ensures the application can handle UI updates while the background thread processes tasks.
Final Thoughts
With this structure, your application will handle thread termination more gracefully on exit. It's essential to ensure any resources allocated by the worker thread are cleaned up appropriately and that the UI does not lock or freeze while waiting for the threads to finish.
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager
import queue
class LaveUi:
def __init__(self, root):
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.submit_button = None
self.app_set_state = True
self.animation_label = tk.Label(self.root)
self.root = root
self.test_handler = None
self.init_event = None
self.queue = queue.Queue() # Queue for UI updates
self.thread = None
self.terminate_thread = False # Flag for thread termination
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord", "SD13_DeleteDashCamRecord",
"SD15_SetAndUnsetDashCamRecordToFavourite", "SD21_MemoriesRecordingSaving",
"SD21_MemoriesRecordingDiscarding", "SD22_MemoriesPlayback", "SD24_ExportMemories",
"SD25_SetMemoriesToFavourite", "SD23_DeleteMemories",
"SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest",
"SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Exit button
self.exit_frame = tk.Frame(self.root) # Create a frame for the exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
# Start the input form
self.get_ui_input()
# Start a periodic check for updates
self.check_queue()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self):
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self):
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port=self.grpc_port,
dlt_port=self.dlt_port, secure=self.secure)
# Simulation of long-running tasks
while not self.terminate_thread:
# Dummy placeholder for actual tasks
# Here you would normally call methods from test_handler to run tests
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
if self.thread and self.thread.is_alive():
# Check the thread's status
self.root.after(100, self.check_init_complete)
else:
self.stop_boot_animation() # Hook into your UI logic as needed
def stop_boot_animation(self):
self.loading_label.config(text="Initialization Complete")
def get_ui_input(self):
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# IP Address input
tk.Label(input_frame, text="IP Address").grid(row=0, column=0)
self.ip_address = tk.Entry(input_frame)
self.ip_address.grid(row=0, column=1)
# DLT Port input
tk.Label(input_frame, text="DLT Port").grid(row=1, column=0)
self.dlt_port = tk.Entry(input_frame)
self.dlt_port.grid(row=1, column=1)
# gRPC Port input
tk.Label(input_frame, text="gRPC Port").grid(row=2, column=0)
self.grpc_port = tk.Entry(input_frame)
self.grpc_port.grid(row=2, column=1)
# Secure checkbox
self.var = tk.BooleanVar()
tk.Checkbutton(input_frame, text="Secure", variable=self.var, command=self.secure_selection).grid(row=3, columnspan=2)
# Submit button
self.submit_button = tk.Button(input_frame, text="Submit", command=self.get_user_input)
self.submit_button.grid(row=4, columnspan=2)
def secure_selection(self):
self.secure = self.var.get()
def get_user_input(self):
if self.app_set_state:
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
self.initTestManager()
print("User input:")
print("IP Address:", self.ip_address.get())
print("DLT Port:", self.dlt_port.get())
print("gRPC Port:", self.grpc_port.get())
print("Secure:", self.secure)
def check_queue(self):
try:
while True:
message = self.queue.get_nowait() # Non-blocking get
self.loading_label.config(text=message) # Update the loading label
except queue.Empty:
pass
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Code Overview:
Imports: Necessary libraries for handling the GUI (Tkinter), threading, and file processing.
Class Definition: The LaveUi class contains all the logic for the user interface and threading.
Initialization: Initial setup includes defining UI components, input fields, and the main Tk() window properties.
Thread Management:
Threads are created for long-running tasks (like running integration tests).
A termination flag (self.terminate_thread) ensures that the thread can exit cleanly when the user decides to close the application.
User Input Handling: UI fields for user input, including IP address, DLT port, and gRPC port.
Graceful Exit: The exit_ui_application method checks if the thread is alive and joins it, ensuring that it finishes before quitting the app.
Check Queue Method: This method continually checks for messages that may be sent from the worker thread to update the UI.
Note:
Ensure you define the IntegrationTestManager class in the integration_test_manager module with appropriate methods that handle test execution.
The image loading and animation methods were omitted in this full example for clarity but can be added based on your previous requirements. Feel free to incorporate them back.
Now you have a complete, structured application that handles threading appropriately, ensuring it remains responsive while performing long-running tasks.
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager # Placeholder for your actual manager
import queue
class LaveUi:
def __init__(self, root):
self.root = root
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Initialize class variables
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.app_set_state = True
self.init_event = None
self.checkbox_frame = None
self.test_handler = None
self.terminate_thread = False # Flag to signal thread termination
self.thread = None
self.queue = queue.Queue() # Queue for UI updates
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord",
"SD13_DeleteDashCamRecord", "SD15_SetAndUnsetDashCamRecordToFavourite",
"SD21_MemoriesRecordingSaving", "SD21_MemoriesRecordingDiscarding",
"SD22_MemoriesPlayback", "SD24_ExportMemories", "SD25_SetMemoriesToFavourite",
"SD23_DeleteMemories", "SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest", "SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Animation variables
self.images = [] # List to hold animation images
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Exit button
self.exit_frame = tk.Frame(self.root) # Create a frame for the exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
self.get_ui_input() # Initialize user input fields
# Start a periodic check for updates
self.check_queue()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port=self.grpc_port,
dlt_port=self.dlt_port, secure=self.secure
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
""" Check if the initialization thread is complete. """
if self.thread and self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the animation when initialization is complete
def stop_boot_animation(self):
""" Stop the boot animation. """
self.animation_running = False
self.animation_label.config(image='') # Clear the label when stopping
self.loading_label.config(text='Initialization Complete')
self.create_checkbox_list() # Create checkbox list after boot animation
def load_animation_images(self):
""" Load animation images from a directory. """
directory = "boot_images" # Directory containing boot images
for i in range(1, 30): # Assuming you have images named 1.png to 29.png
img_path = os.path.join(directory, f'{i}.png')
img = Image.open(img_path)
img = img.convert("RGBA") # Ensure image has alpha channel
# Resize image for display
img = img.resize((100, 50), Image.LANCZOS) # Use high-quality downsampling
self.images.append(ImageTk.PhotoImage(img)) # Store PhotoImage
def start_boot_animation(self):
""" Start the boot animation. """
self.update_animation()
self.root.after(100) # Initial delay
def update_animation(self):
""" Update the animation label. """
if self.animation_running:
# Update the image shown in the label
self.animation_label.config(image=self.images[self.image_index])
self.image_index = (self.image_index + 1) % len(self.images)
self.root.after(100, self.update_animation) # Change image every 100ms
def get_ui_input(self):
""" Create UI elements for user input. """
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# Labels and Entry for IP Address
tk.Label(input_frame, text="IP Address").grid(row=0, column=0)
self.ip_address = tk.Entry(input_frame)
self.ip_address.grid(row=0, column=1)
# Labels and Entry for DLT Port
tk.Label(input_frame, text="DLT Port").grid(row=1, column=0)
self.dlt_port = tk.Entry(input_frame)
self.dlt_port.grid(row=1, column=1)
# Labels and Entry for gRPC Port
tk.Label(input_frame, text="gRPC Port").grid(row=2, column=0)
self.grpc_port = tk.Entry(input_frame)
self.grpc_port.grid(row=2, column=1)
# Checkbox for secure option
self.var = tk.BooleanVar()
tk.Checkbutton(input_frame, text="Secure", variable=self.var, command=self.secure_selection).grid(row=3, columnspan=2)
# Submit button
self.submit_button = tk.Button(input_frame, text="Submit", command=self.get_user_input)
self.submit_button.grid(row=4, columnspan=2)
def secure_selection(self):
""" Handle the secure checkbox selection. """
self.secure = self.var.get()
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
self.initTestManager()
# Print user input for debugging
print("User input:")
print("IP Address:", self.ip_address.get())
print("DLT Port:", self.dlt_port.get())
print("gRPC Port:", self.grpc_port.get())
print("Secure:", self.secure)
def create_checkbox_list(self):
""" Create a list of checkboxes for testing options. """
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# Checkbox for "All" option
self.all_app = tk.BooleanVar()
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def checkbox_toggled(self, index):
""" Handle checkbox toggling event. """
if self.check_vars[index].get(): # If checkbox is checked
method_name = self.checkbox_names[index] # Get the method name
# Call the corresponding method if it exists
if self.test_handler:
method = getattr(self.test_handler, method_name, None)
if method:
method() # Call the method
else:
self.show_toast()
print(f"Method {method_name} is not defined in IntegrationTestManager.")
else:
print("Test Application Init In Complete..")
@staticmethod
def show_toast():
""" Show a notification to the user. """
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
def check_queue(self):
""" Check the queue for UI updates. """
try:
while True:
message = self.queue.get_nowait() # Non-blocking get
self.loading_label.config(text=message) # Update the loading label
except queue.Empty:
pass
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Summary of Key Features
UI Components:
The application defines a class LaveUi that initializes the main Tkinter window and creates various UI components, such as entry fields for user inputs, a loading label, and checkboxes.
Animations:
The application loads images for boot animation and displays them while the application initializes. The animation stops when the initialization is complete.
Thread Handling:
Long-running tasks (like integration tests) are run in a separate thread to keep the UI responsive.
A boolean flag (self.terminate_thread) is set anytime the application is about to close, allowing the thread to exit cleanly.
The main thread joins the worker thread upon exit to ensure that all resources are properly cleaned up.
User Input Handling:
The user inputs are handled and passed to the IntegrationTestManager as needed.
Periodic Queue Checking:
The application checks a queue periodically for message updates to dynamically change UI elements, ensuring that the UI remains responsive during long operations.
Adjustments You Can Make:
Integration Test Management:
Ensure that the IntegrationTestManager class contains the appropriate methods that correspond to the checkbox names so that operations can be executed correctly.
Error Handling:
You may want to enhance error handling for various operations, especially in thread execution.
Resource Management:
Ensure you handle the cleanup of resources in your exit_ui_application method if your integration manager requires specific teardown logic.
By incorporating these elements, your Tkinter application should handle UI updates smoothly, even during long-running operations managed in a separate thread.
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager # Placeholder for your actual manager
import queue
class LaveUi:
def __init__(self, root):
self.root = root
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Initialize class variables
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.app_set_state = True
self.init_event = None
self.checkbox_frame = None
self.test_handler = None
self.terminate_thread = False # Flag to signal thread termination
self.thread = None
self.queue = queue.Queue() # Queue for UI updates
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord",
"SD13_DeleteDashCamRecord", "SD15_SetAndUnsetDashCamRecordToFavourite",
"SD21_MemoriesRecordingSaving", "SD21_MemoriesRecordingDiscarding",
"SD22_MemoriesPlayback", "SD24_ExportMemories", "SD25_SetMemoriesToFavourite",
"SD23_DeleteMemories", "SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest", "SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Animation variables
self.images = [] # List to hold animation images
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Exit button
self.exit_frame = tk.Frame(self.root) # Create a frame for the exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
self.get_ui_input() # Initialize user input fields
# Start a periodic check for updates
self.check_queue()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port=self.grpc_port,
dlt_port=self.dlt_port, secure=self.secure
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
""" Check if the initialization thread is complete. """
if self.thread and self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the animation when initialization is complete
def stop_boot_animation(self):
""" Stop the boot animation. """
self.animation_running = False
self.animation_label.config(image='') # Clear the label when stopping
self.loading_label.config(text='Initialization Complete')
self.create_checkbox_list() # Create checkbox list after boot animation
def load_animation_images(self):
""" Load animation images from a directory. """
directory = "boot_images" # Directory containing boot images
for i in range(1, 30): # Assuming you have images named 1.png to 29.png
img_path = os.path.join(directory, f'{i}.png')
img = Image.open(img_path)
img = img.convert("RGBA") # Ensure image has alpha channel
# Resize image for display
img = img.resize((100, 50), Image.LANCZOS) # Use high-quality downsampling
self.images.append(ImageTk.PhotoImage(img)) # Store PhotoImage
def start_boot_animation(self):
""" Start the boot animation. """
self.update_animation()
self.root.after(100) # Initial delay
def update_animation(self):
""" Update the animation label. """
if self.animation_running:
# Update the image shown in the label
self.animation_label.config(image=self.images[self.image_index])
self.image_index = (self.image_index + 1) % len(self.images)
self.root.after(100, self.update_animation) # Change image every 100ms
def get_ui_input(self):
""" Create UI elements for user input. """
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# Labels and Entry for IP Address
tk.Label(input_frame, text="IP Address").grid(row=0, column=0)
self.ip_address = tk.Entry(input_frame)
self.ip_address.grid(row=0, column=1)
# Labels and Entry for DLT Port
tk.Label(input_frame, text="DLT Port").grid(row=1, column=0)
self.dlt_port = tk.Entry(input_frame)
self.dlt_port.grid(row=1, column=1)
# Labels and Entry for gRPC Port
tk.Label(input_frame, text="gRPC Port").grid(row=2, column=0)
self.grpc_port = tk.Entry(input_frame)
self.grpc_port.grid(row=2, column=1)
# Labels and Entry for Software Version
tk.Label(input_frame, text="Software Version").grid(row=3, column=0)
self.software_ver = tk.Entry(input_frame)
self.software_ver.grid(row=3, column=1)
# Checkbox for secure option
self.var = tk.BooleanVar()
tk.Checkbutton(input_frame, text="Secure", variable=self.var, command=self.secure_selection).grid(row=4, columnspan=2)
# Submit button
self.submit_button = tk.Button(input_frame, text="Submit", command=self.get_user_input)
self.submit_button.grid(row=5, columnspan=2)
def secure_selection(self):
""" Handle the secure checkbox selection. """
self.secure = self.var.get()
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
self.initTestManager()
# Print user input for debugging
print("User input:")
print("IP Address:", self.ip_address.get())
print("DLT Port:", self.dlt_port.get())
print("gRPC Port:", self.grpc_port.get())
print("Software Version:", self.software_ver.get())
print("Secure:", self.secure)
def create_checkbox_list(self):
""" Create a list of checkboxes for testing options. """
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# Checkbox for "All" option
self.all_app = tk.BooleanVar()
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def checkbox_toggled(self, index):
""" Handle checkbox toggling event. """
if self.check_vars[index].get(): # If checkbox is checked
method_name = self.checkbox_names[index] # Get the method name
# Call the corresponding method if it exists
if self.test_handler:
method = getattr(self.test_handler, method_name, None)
if method:
method() # Call the method
else:
self.show_toast()
print(f"Method {method_name} is not defined in IntegrationTestManager.")
else:
print("Test Application Initialization In Complete..")
@staticmethod
def show_toast():
""" Show a notification to the user. """
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
def check_queue(self):
""" Check the queue for UI updates. """
try:
while True:
message = self.queue.get_nowait() # Non-blocking get
self.loading_label.config(text=message) # Update the loading label
except queue.Empty:
pass
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Key Changes Made:
Software Version Entry:
Added a label and entry field for "Software Version" in the get_ui_input method, positioning it appropriately in the UI grid.
Other Overview:
The application maintains its earlier features: boot animation, integrated checkbox options, user input handling, and responsive design through threading.
A queue is implemented for UI updates, allowing the main thread to remain responsive during longer operations.
All user inputs, including IP address, DLT port, gRPC port, and software version, are captured for later use in the integration test manager.
With this complete code in hand, you should be able to run your Tkinter application, including all required UI components and the requested software version entry. If you need further enhancements or modifications, feel free to ask!
Complete Context with Animation Code
Here’s an example of how to integrate this into the complete Tkinter application:
python
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager # Placeholder for your actual manager
import queue
class LaveUi:
def __init__(self, root):
self.root = root
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Initialize class variables
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.app_set_state = True
self.checkbox_frame = None
self.test_handler = None
self.terminate_thread = False # Flag to signal thread termination
self.thread = None
self.queue = queue.Queue() # Queue for UI updates
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord",
"SD13_DeleteDashCamRecord", "SD15_SetAndUnsetDashCamRecordToFavourite",
"SD21_MemoriesRecordingSaving", "SD21_MemoriesRecordingDiscarding",
"SD22_MemoriesPlayback", "SD24_ExportMemories", "SD25_SetMemoriesToFavourite",
"SD23_DeleteMemories", "SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest", "SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Animation variables
self.images = [] # List to hold animation images
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
# Loading text
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Exit button
self.exit_frame = tk.Frame(self.root) # Create a frame for the exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
self.get_ui_input() # Initialize user input fields
# Start a periodic check for updates
self.check_queue()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager)
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=self.ip_address.get(), grpc_port=self.grpc_port,
dlt_port=self.dlt_port, secure=self.secure
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
""" Check if the initialization thread is complete. """
if self.thread and self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the animation when initialization is complete
def stop_boot_animation(self):
""" Stop the boot animation. """
self.animation_running = False
self.animation_label.config(image='') # Clear the label when stopping
self.loading_label.config(text='Initialization Complete')
self.create_checkbox_list() # Create checkbox list after boot animation
def load_animation_images(self):
""" Load animation images from a directory. """
directory = "boot_images" # Directory containing boot images
for i in range(1, 30): # Assuming you have images named 1.png to 29.png
img_path = os.path.join(directory, f'{i}.png')
# Open the image
img = Image.open(img_path)
# Ensure the image has an alpha channel
img = img.convert("RGBA") # Convert to RGBA format
datas = img.getdata() # Get the pixel data
new_data = []
for item in datas:
# Modify this part to set the specific background color you want to remove
# For example, remove white background (255, 255, 255)
if item[0] > 240 and item[1] > 240 and item[2] > 240: # Check for near-white colors
new_data.append((255, 255, 255, 0)) # Change to transparent
else:
new_data.append(item)
img.putdata(new_data) # Update the image data
img = img.resize((100, 50), Image.LANCZOS) # Resize for display
self.images.append(ImageTk.PhotoImage(img)) # Store the PhotoImage in the list
def start_boot_animation(self):
""" Start the boot animation. """
self.update_animation()
self.root.after(100) # Initial delay
def update_animation(self):
""" Update the animation label. """
if self.animation_running:
# Update the image shown in the label
self.animation_label.config(image=self.images[self.image_index])
self.image_index = (self.image_index + 1) % len(self.images)
self.root.after(100, self.update_animation) # Change image every 100ms
def get_ui_input(self):
""" Create UI elements for user input. """
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# Labels and Entry for IP Address
tk.Label(input_frame, text="IP Address").grid(row=0, column=0)
self.ip_address = tk.Entry(input_frame)
self.ip_address.grid(row=0, column=1)
# Labels and Entry for DLT Port
tk.Label(input_frame, text="DLT Port").grid(row=1, column=0)
self.dlt_port = tk.Entry(input_frame)
self.dlt_port.grid(row=1, column=1)
# Labels and Entry for gRPC Port
tk.Label(input_frame, text="gRPC Port").grid(row=2, column=0)
self.grpc_port = tk.Entry(input_frame)
self.grpc_port.grid(row=2, column=1)
# Labels and Entry for Software Version
tk.Label(input_frame, text="Software Version").grid(row=3, column=0)
self.software_ver = tk.Entry(input_frame)
self.software_ver.grid(row=3, column=1)
# Checkbox for secure option
self.var = tk.BooleanVar()
tk.Checkbutton(input_frame, text="Secure", variable=self.var, command=self.secure_selection).grid(row=4, columnspan=2)
# Submit button
self.submit_button = tk.Button(input_frame, text="Submit", command=self.get_user_input)
self.submit_button.grid(row=5, columnspan=2)
def secure_selection(self):
""" Handle the secure checkbox selection. """
self.secure = self.var.get()
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
self.initTestManager()
# Print user input for debugging
print("User input:")
print("IP Address:", self.ip_address.get())
print("DLT Port:", self.dlt_port.get())
print("gRPC Port:", self.grpc_port.get())
print("Software Version:", self.software_ver.get())
print("Secure:", self.secure)
def create_checkbox_list(self):
""" Create a list of checkboxes for testing options. """
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# Checkbox for "All" option
self.all_app = tk.BooleanVar()
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def checkbox_toggled(self, index):
""" Handle checkbox toggling event. """
if self.check_vars[index].get(): # If checkbox is checked
method_name = self.checkbox_names[index] # Get the method name
# Call the corresponding method if it exists
if self.test_handler:
method = getattr(self.test_handler, method_name, None)
if method:
method() # Call the method
else:
self.show_toast()
print(f"Method {method_name} is not defined in IntegrationTestManager.")
else:
print("Test Application Initialization In Complete..")
@staticmethod
def show_toast():
""" Show a notification to the user. """
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
def check_queue(self):
""" Check the queue for UI updates. """
try:
while True:
message = self.queue.get_nowait() # Non-blocking get
self.loading_label.config(text=message) # Update the loading label
except queue.Empty:
pass
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Explanation of Changes
Transparency Handling in load_animation_images:
The img.convert("RGBA") line ensures the image has an alpha channel.
The algorithm for checking for white and near-white colors has been applied to set those pixels to transparent.
Image Resizing: The resizing maintains the RGBA format to ensure the alpha channel is preserved.
Check for High Values: The color removal logic checks for pixel values that are mostly white (greater than 240 for each RGB component) to convert them to transparent.
Important Note
Make sure your images in the specified boot_images directory are actually in a format that supports transparency, such as PNG files. If they are in another format lacking alpha support, the transparency will not render correctly.
If issues persist, check the images with software that can confirm their alpha transparency presence, and if possible, simplify the test with a hard-coded image that definitely has transparency to isolate any potential issues.
Ensure the Method is Defined
If you are using self.enable_full_execution_test in your create_checkbox_list, make sure to define this method in your class. Here's a basic template for it:
python
def enable_full_execution_test(self):
""" Enable full execution when 'All' checkbox is checked. """
self.enable_full_execution = self.all_app.get() # Getting value from the checkbox
Full Context Integration
Here is how these changes could integrate into the overall code structure:
python
# Inside your LaveUi class...
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
# Get user inputs
ip_address = self.ip_address.get() # Correctly getting the value
dlt_port = self.dlt_port.get() # Get value directly
grpc_port = self.grpc_port.get() # Get value directly
software_ver = self.software_ver.get() # Get value directly
# Print user input for debugging
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
# Now pass the values to the test manager if required
self.initTestManager() # Start the test manager with the gathered values
def enable_full_execution_test(self):
""" Enable full execution when 'All' checkbox is checked. """
self.enable_full_execution = self.all_app.get() # Getting value from the checkbox
Conclusion
Make sure you:
Retrieve the user input values before storing them in their respective attributes.
Define any methods you reference in your commands, like enable_full_execution_test, to avoid runtime errors.
With these changes, your code should work without the AttributeError you encountered. If you have further issues or more specific features you'd like to implement, feel free to ask!
If your initTestManager function accepts parameters (which seems like it should if you're passing in values), make sure to adjust it accordingly. Here’s an updated snippet:
python
def initTestManager(self, ip_address, dlt_port, grpc_port, software_ver):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager, args=(ip_address, dlt_port, grpc_port, software_ver))
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
3. Update Your run_integration_test_manager Method
You must ensure that the run_integration_test_manager method takes parameters and uses them correctly. Update it as follows:
python
def run_integration_test_manager(self, ip_address, dlt_port, grpc_port, software_ver):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=ip_address, # Use the passed IP address
grpc_port=grpc_port, # Use the passed gRPC port string
dlt_port=dlt_port, # Use the integer DLT port
secure=self.secure
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
Conclusion
With these changes:
You convert the DLT port value retrieved from the Entry widget to an integer before using it.
You ensure that parameters are being passed correctly between methods.
This should resolve the issue of trying to use a GUI widget directly in a context that expects an integer (like a port number for a server). If you encounter further issues, let me know!
# Assuming this is defined in the 'integration_test_manager.py' file.
class IntegrationTestManager:
def __init__(self, d_can_dbc_file_path: str, p_can_dbc_file_path: str,
server_ip="10.0.8.225", grpc_port="8866", dlt_port=3490, secure=False, cycle_id=""):
self.d_can_dbc_file_path = d_can_dbc_file_path
self.p_can_dbc_file_path = p_can_dbc_file_path
self.server_ip = server_ip
self.grpc_port = grpc_port
self.dlt_port = dlt_port
self.secure = secure
self.cycle_id = cycle_id
# Initialize connection, set up other resources, etc.
# Inside the LaveUi class...
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
# Get user inputs
ip_address = self.ip_address.get() # Get the IP address
# Convert DLT port to an integer, handle potential conversion errors
try:
dlt_port = int(self.dlt_port.get()) # Convert DLT port to an integer
except ValueError:
print("Invalid DLT Port. Please enter a valid integer.")
return # Exit if the conversion fails
grpc_port = self.grpc_port.get() # Get gRPC port as string directly
software_ver = self.software_ver.get() # Get software version as string
# Print user input for debugging
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
# Start the test manager with the gathered values
self.initTestManager(ip_address, dlt_port, grpc_port, software_ver)
def initTestManager(self, ip_address, dlt_port, grpc_port, software_ver):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager, args=(ip_address, dlt_port, grpc_port, software_ver))
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self, ip_address, dlt_port, grpc_port, software_ver):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=ip_address, # Using the user input IP address
grpc_port=grpc_port, # Using the user input gRPC port
dlt_port=dlt_port, # Using the integer DLT port
secure=self.secure # Using the secure option
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
Key Changes Made:
Input Conversion:
Ensure to capture the DLT port input as an integer. Added error handling to check if the conversion to an integer is valid.
Parameter Passing:
Pass the parameters from get_user_input directly to initTestManager.
Initialization of IntegrationTestManager:
In run_integration_test_manager, create an instance of IntegrationTestManager using user-provided inputs.
Error Resolution:
This structure should resolve the errors you're encountering by ensuring that:
You are passing properly typed values to the IntegrationTestManager.
You check for potential conversion errors, providing feedback to users if they input incorrect data.
If you encounter further issues or need additional functionality, feel free to reach out!
import os
import threading
import tkinter as tk
from plyer import notification
from PIL import Image, ImageTk
from integration_test_manager import IntegrationTestManager # Ensure this is correctly implemented
import queue
class LaveUi:
def __init__(self, root):
self.root = root
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Initialize class variables
self.enable_full_execution = False
self.all_app = None
self.var = None
self.secure = False
self.app_set_state = True
self.init_event = None
self.checkbox_frame = None
self.test_handler = None
self.terminate_thread = False # Flag to signal thread termination
self.thread = None
self.queue = queue.Queue() # Queue for UI updates
# User Input Values
self.ip_address = None
self.dlt_port = 3490
self.grpc_port = "8866"
self.software_ver = None
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
"SD11_CleanupRoutines", "SD11_CleanupRoutinesGeneric", "SD12_DiagnosisCaptureImage",
"SD13_EthernetTest", "SD2_RDIOperation", "SD3_CodingOperation",
"SD4_IOCTLOperation", "SD5_MeasurementOperation", "SD6_AdaptionOperation",
"SD7_EthernetFaultDetection", "SD11_DashCamCrashEvent", "SD11_EmergencyBrakeEvent",
"SD12_DashCamPlayback", "SD14_ExportDashCamRecord",
"SD13_DeleteDashCamRecord", "SD15_SetAndUnsetDashCamRecordToFavourite",
"SD21_MemoriesRecordingSaving", "SD21_MemoriesRecordingDiscarding",
"SD22_MemoriesPlayback", "SD24_ExportMemories", "SD25_SetMemoriesToFavourite",
"SD23_DeleteMemories", "SD1_TelemetryTrackMapRecordingImproperRequest",
"SD1_TelemetryTrackMapRecordingProperRequest", "SD211_TelemetrySectorManagementSelectASectorToEdit",
"SD212_TelemetrySectorManagementAddOrRemoveASector",
"SD213_TelemetrySectorManagementSaveASectorChanges",
"SD213_TelemetrySectorManagementDiscardASectorChanges",
"SD22_TelemetryTrackManagementExportTrackAndSessionsData",
"SD23_TelemetryTrackManagementSetATrackAsFavorite",
"SD23_TelemetryTrackManagementUnsetATrackAsFavorite",
"SD24_ImportTracksAndSessions", "SD31_TelemetrySessionManagementStartSession",
"SD31_TelemetrySessionManagementStartSessionOutOfTrack",
"SD32_TelemetrySessionManagementStopSession",
"SD32_TelemetrySessionManagementStopSessionRaceCanBeSavedFalse",
"SD33_SetSessionAsFavorite", "SD33_UnsetSessionAsFavorite",
"SD34_DeleteSessions", "SD4_TelemetrySessionAnalysisSessionLap",
"SD4_TelemetrySessionAnalysisSessionBest",
"SD4_TelemetrySessionAnalysisPersonalBest", "SD4_TelemetrySessionAnalysisAbsoluteBest",
"SD1_IPSec", "SD2_SecureBoot", "SD3_UartAccess", "SD4_mTLS", "SD1_UpdateLAVU"
]
# Animation variables
self.images = [] # List to hold animation images
self.image_index = 0
self.animation_running = True
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
self.load_animation_images()
self.start_boot_animation()
# Loading text (status label)
self.loading_label = tk.Label(self.root, text="Setup Input Values", font=("Helvetica", 24), fg="red")
self.loading_label.pack(pady=15)
# Exit button
self.exit_frame = tk.Frame(self.root) # Create a frame for the exit button
self.exit_frame.pack(side=tk.BOTTOM, pady=10) # Pack it to the bottom
self.exit_button()
self.get_ui_input() # Initialize user input fields
# Start a periodic check for updates in the queue
self.check_queue()
def exit_button(self):
exit_button = tk.Button(self.exit_frame, text="Exit", command=self.exit_ui_application)
exit_button.pack(pady=10)
def exit_ui_application(self):
print("UI Application Exit !!")
# Set the flag to terminate the thread
self.terminate_thread = True
# If there's a thread running, join it
if self.thread and self.thread.is_alive():
self.thread.join(timeout=5) # Wait for the thread to finish
if self.thread.is_alive():
print("Thread did not finish in time, proceeding to exit.")
self.root.quit()
def initTestManager(self, ip_address, dlt_port, grpc_port, software_ver):
""" Initialize Integration Test Manager in a separate thread. """
self.terminate_thread = False
self.thread = threading.Thread(target=self.run_integration_test_manager, args=(ip_address, dlt_port, grpc_port, software_ver))
self.thread.start() # Start the initialization in a separate thread
self.root.after(100, self.check_init_complete) # Initial check for completion
def run_integration_test_manager(self, ip_address, dlt_port, grpc_port, software_ver):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=ip_address, # Using the user input IP address
grpc_port=grpc_port, # Using the user input gRPC port
dlt_port=dlt_port, # Using the integer DLT port
secure=self.secure # Using the secure option
)
# Simulate long-running task
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
""" Check if the initialization thread is complete. """
if self.thread and self.thread.is_alive():
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the animation when initialization is complete
def stop_boot_animation(self):
""" Stop the boot animation. """
self.animation_running = False
self.animation_label.config(image='') # Clear the label when stopping
self.loading_label.config(text='Initialization Complete')
self.create_checkbox_list() # Create checkbox list after boot animation
def load_animation_images(self):
""" Load animation images from a directory. """
directory = "boot_images" # Directory containing boot images
for i in range(1, 30): # Assuming you have images named 1.png to 29.png
img_path = os.path.join(directory, f'{i}.png')
# Open the image
img = Image.open(img_path)
# Ensure the image has an alpha channel
img = img.convert("RGBA") # Convert to RGBA format
datas = img.getdata() # Get the pixel data
new_data = []
for item in datas:
# Modify this part to set the specific background color you want to remove
# For example, remove white background (greater than 240 in RGB)
if item[0] > 240 and item[1] > 240 and item[2] > 240:
new_data.append((255, 255, 255, 0)) # Change to transparent
else:
new_data.append(item)
img.putdata(new_data) # Update the image data
img = img.resize((100, 50), Image.LANCZOS) # Resize for display
self.images.append(ImageTk.PhotoImage(img)) # Store the PhotoImage in the list
def start_boot_animation(self):
""" Start the boot animation. """
self.update_animation()
self.root.after(100) # Initial delay
def update_animation(self):
""" Update the animation label. """
if self.animation_running:
# Update the image shown in the label
self.animation_label.config(image=self.images[self.image_index])
self.image_index = (self.image_index + 1) % len(self.images)
self.root.after(100, self.update_animation) # Change image every 100ms
def get_ui_input(self):
""" Create UI elements for user input. """
input_frame = tk.Frame(self.root)
input_frame.pack(pady=20) # Add some vertical padding
# Labels and Entry for IP Address
tk.Label(input_frame, text="IP Address").grid(row=0, column=0)
self.ip_address = tk.Entry(input_frame)
self.ip_address.grid(row=0, column=1)
# Labels and Entry for DLT Port
tk.Label(input_frame, text="DLT Port").grid(row=1, column=0)
self.dlt_port = tk.Entry(input_frame)
self.dlt_port.grid(row=1, column=1)
# Labels and Entry for gRPC Port
tk.Label(input_frame, text="gRPC Port").grid(row=2, column=0)
self.grpc_port = tk.Entry(input_frame)
self.grpc_port.grid(row=2, column=1)
# Labels and Entry for Software Version
tk.Label(input_frame, text="Software Version").grid(row=3, column=0)
self.software_ver = tk.Entry(input_frame)
self.software_ver.grid(row=3, column=1)
# Checkbox for secure option
self.var = tk.BooleanVar()
tk.Checkbutton(input_frame, text="Secure", variable=self.var, command=self.secure_selection).grid(row=4, columnspan=2)
# Submit button
self.submit_button = tk.Button(input_frame, text="Submit", command=self.get_user_input)
self.submit_button.grid(row=5, columnspan=2)
def secure_selection(self):
""" Handle the secure checkbox selection. """
self.secure = self.var.get()
def get_user_input(self):
""" Gather user input and start the test manager. """
if self.app_set_state:
# Update the loading label
self.loading_label.config(text="Application Initialization in Progress !!")
self.app_set_state = False
# Get user inputs
ip_address = self.ip_address.get() # Get the IP address
# Convert DLT port to an integer, handle potential conversion errors
try:
dlt_port = int(self.dlt_port.get()) # Convert DLT port to an integer
except ValueError:
print("Invalid DLT Port. Please enter a valid integer.")
return # Exit if the conversion fails
grpc_port = self.grpc_port.get() # Get gRPC port as string directly
software_ver = self.software_ver.get() # Get software version as string
# Print user input for debugging
print("User input:")
print("IP Address:", ip_address)
print("DLT Port:", dlt_port)
print("gRPC Port:", grpc_port)
print("Software Version:", software_ver)
print("Secure:", self.secure)
# Start the test manager with the gathered values
self.initTestManager(ip_address, dlt_port, grpc_port, software_ver)
def create_checkbox_list(self):
""" Create a list of checkboxes for testing options. """
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# Checkbox for "All" option
self.all_app = tk.BooleanVar()
checkbox_all = tk.Checkbutton(
self.checkbox_frame,
text="All",
variable=self.all_app,
command=self.enable_full_execution_test
)
checkbox_all.grid(row=0, column=0, columnspan=4, sticky='w', padx=10, pady=5)
# Create Checkboxes in four columns
for i in range(len(self.checkbox_names)):
row = (i // 4) + 1
column = i % 4
checkbox = tk.Checkbutton(
self.checkbox_frame,
text=self.checkbox_names[i],
variable=self.check_vars[i],
command=lambda i=i: self.checkbox_toggled(i) # Pass the index
)
checkbox.grid(row=row, column=column, sticky='w', padx=10, pady=5)
# Configure the grid columns
for col in range(4):
self.checkbox_frame.grid_columnconfigure(col, weight=1)
def checkbox_toggled(self, index):
""" Handle checkbox toggling event. """
if self.check_vars[index].get(): # If checkbox is checked
method_name = self.checkbox_names[index] # Get the method name
# Call the corresponding method if it exists
if self.test_handler:
method = getattr(self.test_handler, method_name, None)
if method:
method() # Call the method
else:
self.show_toast()
print(f"Method {method_name} is not defined in IntegrationTestManager.")
else:
print("Test Application Initialization In Complete..")
@staticmethod
def show_toast():
""" Show a notification to the user. """
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
def check_queue(self):
""" Check the queue for UI updates. """
try:
while True:
message = self.queue.get_nowait() # Non-blocking get
self.loading_label.config(text=message) # Update the loading label
except queue.Empty:
pass
self.root.after(100, self.check_queue) # Check the queue every 100ms
# Code to run the application
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
root.mainloop()
Key Features in the Code:
User Input Handling:
Successfully gathers user inputs for the IP address, DLT port, gRPC port, and software version, with validation and conversion of the DLT port.
Button and Checkbox Implementation:
Features buttons for exiting and submitting the configuration, along with a checkbox for a "Secure" option.
Animation Handling:
Displays a boot animation with support for transparent images.
Threading:
Runs the integration test manager in a separate thread to keep the UI responsive during long-running operations.
Error Handling:
Catches value errors to prevent application crashes due to invalid user input.
Notes:
Ensure that IntegrationTestManager is correctly implemented and that it can handle the parameters you're passing to it.
Make sure the image files for the animation are present in the boot_images directory and support RGBA format.
With this full implementation, you should have a functional Tkinter application that gathers user inputs, initiates tests, and maintains responsiveness through threading. If you have any additional requirements or questions, feel free to ask!
True
check_init_complete
Here’s how you can implement it:
python
def run_integration_test_manager(self, ip_address, dlt_port, grpc_port, software_ver):
""" This method will contain the logic for running the integration tests. """
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=ip_address, # Using the user input IP address
grpc_port=grpc_port, # Using the user input gRPC port
dlt_port=dlt_port, # Using the integer DLT port
secure=self.secure # Using the secure option
)
while not self.terminate_thread:
# Here you would typically call methods from the test handler to perform tests.
# You can also include checks or logic related to the test handling.
pass
print("IntegrationTestManager thread terminated.")
def check_init_complete(self):
""" Check if the initialization thread is complete. """
if self.thread and self.thread.is_alive():
# Check init_event for completion
if self.test_handler and self.test_handler.init_event:
self.stop_boot_animation() # Stop when initialization is complete
else:
self.root.after(100, self.check_init_complete) # Keep checking if still running
else:
self.stop_boot_animation() # Stop the animation when initialization is complete
Explanation:
Polling for Initialization: The check_init_complete method not only checks if the thread is alive but also checks self.test_handler.init_event. If it turns true, it will call self.stop_boot_animation().
Calling initialize_status: The method initialize_status inside IntegrationTestManager should include the necessary initialization logic and should set self.init_event to True when done.
Complete Combined Implementation
Here’s a brief summary combining the relevant parts in a more complete context for clarity:
python
class IntegrationTestManager:
def __init__(self, d_can_dbc_file_path: str, p_can_dbc_file_path: str,
server_ip="10.0.8.225", grpc_port="8866", dlt_port=3490, secure=False, cycle_id=""):
self.d_can_dbc_file_path = d_can_dbc_file_path
self.p_can_dbc_file_path = p_can_dbc_file_path
self.server_ip = server_ip
self.grpc_port = grpc_port
self.dlt_port = dlt_port
self.secure = secure
self.cycle_id = cycle_id
self.init_event = False # Initialize to False
self.initialize_status()
def initialize_status(self):
print("IntegrationTestManager: Initializing...")
# Here you would implement your actual initialization logic
# ...
self.init_event = True # Set this to True when initialization is complete
print("IntegrationTestManager: Initialization complete...")
# Inside your LaveUi class...
def run_integration_test_manager(self, ip_address, dlt_port, grpc_port, software_ver):
self.test_handler = IntegrationTestManager(
d_can_dbc_file_path="./can_database/MLBevo_Gen2_MLBevo_DCAN_KMatrix_V8.24.00F_20220602_VP.dbc",
p_can_dbc_file_path="./can_database/PCAN_INFOT_Merged_R20.dbc",
server_ip=ip_address,
grpc_port=grpc_port,
dlt_port=dlt_port,
secure=self.secure
)
# Keep the thread running, performing tests, etc.
while not self.terminate_thread:
pass # Your test logic here
def check_init_complete(self):
if self.thread and self.thread.is_alive():
if self.test_handler and self.test_handler.init_event:
self.stop_boot_animation() # Initialize complete
else:
self.root.after(100, self.check_init_complete) # Continue checking
else:
self.stop_boot_animation() # Called when thread is done
Conclusion
With these updates, your application will now properly check the initialization status of IntegrationTestManager and respond accordingly. If you have specific behaviors that should follow the initialization completion, you can add those within the stop_boot_animation method or trigger additional methods as needed.
If you have further questions or enhancements in mind, feel free to ask!