Creating a boot animation in Python can involve using libraries for graphics and animations. A simple way to create a boot animation is to use the Pygame library, which allows for easy handling of images and animations. Below is a basic example of how to create a simple boot animation using Pygame.
First, make sure you have Pygame installed. You can install it using pip:
bash
pip install pygame
Here's a simple example of a boot animation in Python using Pygame:
python
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up display
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Boot Animation")
# Load your boot images
# Replace 'boot_frame_1.png', 'boot_frame_2.png', etc. with your actual image filenames.
boot_images = []
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img = pygame.image.load(f'boot_frame_{i}.png')
boot_images.append(img)
# Main loop
clock = pygame.time.Clock()
frame_index = 0
image_count = len(boot_images)
animation_duration = 1000 # Milliseconds (1 second)
frames_per_second = 12 # You can adjust this
total_frames = (animation_duration / 1000) * frames_per_second
frame_time = animation_duration / total_frames
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Clear screen
screen.fill((0, 0, 0))
# Draw current boot image
current_image = boot_images[frame_index]
screen.blit(current_image, (screen_width // 2 - current_image.get_width() // 2,
screen_height // 2 - current_image.get_height() // 2))
# Update display
pygame.display.flip()
# Update frame index
frame_index += 1
if frame_index >= image_count:
frame_index = 0 # Loop back to the start of the animation
# Control frame rate
clock.tick(frames_per_second)
pygame.quit()
Steps to Follow:
Images: Create boot images named boot_frame_1.png, boot_frame_2.png, etc. Ensure they are in the same directory as your script or provide full paths.
Run the Script: Execute the script, and it will display a series of images in sequence to create an animation.
Modify as Needed: You can adjust the number of frames, the size of the window, and the duration of the animation as needed.
Note:
The boot images you use should have a similar size and aspect ratio to ensure a smooth animation experience.
Ensure that you handle any necessary cleanup when the animation is finished (like transitioning to the main application, if applicable).
This is a basic example; sophisticated boot animations may incorporate more complex graphics, sound, or transitions.
User
Below is my current code . I need to integrate the boot animation in this . because the IntegrationTestManager takes more time in application startup..
ui.py
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
class LaveUi:
def init(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
init_event = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
code
Assistant
To integrate a boot animation into your existing Tkinter application while the IntegrationTestManager initializes, you can create a separate thread for the animation that runs concurrently with the IntegrationTestManager initialization. Once the initialization is complete, you can stop the animation.
Here’s how you can modify your existing code to include a boot animation using Pygame:
Complete Code Update:
python
User
where the boot animation start it didnt call run ??
Assistant
You're correct; my previous code snippet for integrating the boot animation into your Tkinter application did have a flaw in how it initializes and manages the boot animation thread. I will clarify how to ensure that the boot animation starts correctly in your application.
Key Modifications
Ensure pygame is initialized properly: You need to make sure that the Pygame loop is started correctly.
Control the running state of the Pygame loop: Properly manage the control of the boot animation lifecycle based on whether the IntegrationTestManager has initialized successfully or not.
Here is the corrected version of the code that integrates well with your existing code:
python
User
I didnt need a seperate window.. show in the same window
Assistant
To integrate a boot animation that plays within the same Tkinter window instead of using a separate Pygame window, you can use Tkinter's built-in capabilities in conjunction with PIL (Pillow) to handle image display and animation. This way, the animation can take place in the main Tkinter window without needing to switch to a separate window.
Required Library
First, if you haven't already installed Pillow, you can do so with the following command:
bash
pip install Pillow
Updating Your Current Code
Here's an example of how to integrate a boot animation using images directly in the Tkinter window:
python
User
AttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS'
Assistant
The AttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS' error occurs because the ANTIALIAS constant has been removed in recent versions of the Pillow library (specifically starting from version 10.0.0). Instead, you can simply use Image.LANCZOS or Image.LANCZOS as the resampling filter when resizing images.
Here's the adjusted part of the code to avoid using ANTIALIAS:
Updated Code
Here's the relevant part where the image is resized, with the correct filter:
python
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{i}.png')
img = Image.open(img_path)
img = img.resize((800, 600), Image.LANCZOS) # Use Image.LANCZOS for high-quality downsampling
self.images.append(ImageTk.PhotoImage(img))
Full Example with the Change
Here is the full example with the updated resizing method:
python
User
add text as "App Loading" in the boot time
Assistant
To add a text overlay, such as "App Loading," during the boot animation in your Tkinter application, you can use a Label widget from Tkinter to display the text alongside your animated images. Below is the updated code that includes a text label to indicate that the app is loading:
Full Code with "App Loading" Text
Here’s the complete code incorporating the loading text:
python
User
remove the background of the animation image.png
Assistant
To remove the background of an image in Python, you can use the Pillow library along with some image processing techniques. The typical approach involves using transparency and/or the alpha channel to make parts of the image transparent.
Important Notes on Background Removal:
Image Preparation: The images should ideally have a uniform background color to make it easy to remove. For example, if the background is a single color (e.g., white, black), you can target that color and make it transparent.
New Images: If you need to process multiple PNG images to remove backgrounds, you may want to automate that process outside of your application, but I’ll include an example of how to do it in the application itself.
Manual Preparation: For complex images (like those with gradients), manual preparation using an image editing tool (like Photoshop, GIMP, or an online background remover) might be necessary before loading them into your application.
Code to Load Images with Background Transparency
Below is an updated version of your loading function that accounts for images with a transparent background:
python
User
change the text colour
Assistant
To change the text color of the "App Loading" label in your Tkinter application, you can specify the fg (foreground) parameter when creating the Label widget. You can set it to any valid color name (like "red", "blue", "green", etc.) or you can use hexadecimal color codes.
Changing Text Color
Here’s how you can modify the loading_label to set the text color. For example, let's change the text color to green:
python
# Loading text with specified foreground color
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24), fg="green")
Full Example with Custom Text Color
Here's the complete code with the modified loading text color:
python
User
create_checkbox_list should active after the boot animation stops
Assistant
To ensure that the checkbox list in your Tkinter application is created after the boot animation stops, you can modify the application flow to delay the creation of the checkbox list until the IntegrationTestManager initialization is complete and the boot animation has stopped.
Steps to Achieve This:
Remove the call to create_checkbox_list() from the constructor of your LaveUi class.
Call create_checkbox_list() after stopping the boot animation. This ensures that the checkboxes will only be created after the loading phase is completed.
Updated Code
Below is the updated version of your code reflecting these changes:
python
User
A text box to add a get a text in this code
Assistant
To add a text box (an Entry widget) in your Tkinter application where users can input text, you can follow these steps:
Create an Entry widget: This will allow the user to input text.
Add functionality to retrieve the input: You can create a button that, when clicked, retrieves the text from the Entry widget.
Updated Code with an Entry Widget
Here’s how you can incorporate an Entry widget into your existing code:
# 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"
]
self.initTestManager()
self.create_checkbox_list()
def exit_button(self):
# Button to exit the application
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@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 create_checkbox_list(self):
# Create a frame for the checkbox list
self.checkbox_frame = tk.Frame(self.root)
self.checkbox_frame.pack(pady=20)
# 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)
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.init_handler:
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 Progress..")
def run_integration_test_manager(self, init_evnt):
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=init_evnt)
def initTestManager(self):
self.init_event = threading.Event()
self.thread = threading.Thread(target=self.run_integration_test_manager, args=(self.init_event,))
self.thread.start() # Start the initialization in a separate thread
# self.init_event.wait()
self.init_handler = True
def deinitTestManager(self):
self.thread.join()
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
import pygame
import os
import time
class BootAnimation:
def __init__(self):
self.running = True
self.images = []
self.load_images()
self.screen = None
self.clock = None
def load_images(self):
# Put your boot images in this folder or give the full path
directory = "boot_images"
self.images = [pygame.image.load(os.path.join(directory, f'boot_frame_{i}.png'))
for i in range(1, 6)] # Load images named boot_frame_1.png to boot_frame_5.png
def run(self):
pygame.init()
self.screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Boot Animation")
self.clock = pygame.time.Clock()
frame_index = 0
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# Draw current boot image
self.screen.fill((0, 0, 0))
self.screen.blit(self.images[frame_index], (400 - self.images[frame_index].get_width() // 2,
300 - self.images[frame_index].get_height() // 2))
pygame.display.flip()
frame_index = (frame_index + 1) % len(self.images)
self.clock.tick(10) # Change the frame rate if needed
pygame.quit()
def stop(self):
self.running = False
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
# (Your checkbox names here...)
]
self.boot_animation = BootAnimation()
self.start_boot_animation() # Start boot animation
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def start_boot_animation(self):
self.animation_thread = threading.Thread(target=self.boot_animation.run)
self.animation_thread.start()
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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.boot_animation.stop() # Stop the boot animation
self.animation_thread.join() # Wait for the animation thread to finish
def deinitTestManager(self):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Key Changes and Additions:
New BootAnimation Class: Created to handle the boot animation using Pygame. This class loads images and runs the animation.
Load Images: Ensure you have images named boot_frame_1.png, boot_frame_2.png, etc., in a directory named boot_images. Adjust the image loading code if your images are located elsewhere.
Start animation in a thread: The start_boot_animation method initializes and starts the boot animation in a separate thread.
Monitor Initialization: The check_init_complete method is called periodically (every 100ms) to check if the integration test manager has finished initializing. Once it has, the animation stops.
Stop the Animation: When initialization is complete, the animation is stopped, and the animation thread is joined to clean up properly.
Make sure to customize paths and images as per your application's needs.
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
import pygame
import os
import time
class BootAnimation:
def __init__(self):
self.running = True
self.images = []
self.load_images()
self.screen = None
self.clock = None
def load_images(self):
# Put your boot images in this folder or give the full path
directory = "boot_images" # Make sure this folder contains the images
self.images = [pygame.image.load(os.path.join(directory, f'boot_frame_{i}.png'))
for i in range(1, 6)] # Load images named boot_frame_1.png to boot_frame_5.png
def run(self):
pygame.init()
self.screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Boot Animation")
self.clock = pygame.time.Clock()
frame_index = 0
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# Draw current boot image
self.screen.fill((0, 0, 0))
self.screen.blit(self.images[frame_index], (400 - self.images[frame_index].get_width() // 2,
300 - self.images[frame_index].get_height() // 2))
pygame.display.flip()
frame_index = (frame_index + 1) % len(self.images)
self.clock.tick(10) # Change the frame rate if needed
pygame.quit()
def stop(self):
self.running = False
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# Variable list for checkboxes
self.check_vars = [tk.BooleanVar() for _ in range(48)]
self.checkbox_names = [
# Add checkbox names here...
]
# Start boot animation
self.boot_animation = BootAnimation()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def start_boot_animation(self):
self.animation_thread = threading.Thread(target=self.boot_animation.run)
self.animation_thread.start()
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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.boot_animation.stop() # Stop the boot animation
self.animation_thread.join() # Wait for the animation thread to finish
def deinitTestManager(self):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Explanation of Key Components:
BootAnimation Class: This class manages loading and displaying the boot images using Pygame. Make sure the images are available in the folder you specify.
Start Boot Animation: The start_boot_animation method starts the animation in a new thread.
Pygame Loop: The run method inside BootAnimation initializes Pygame, enters a loop to display images, and checks events until self.running is set to False.
Thread Completion: After the IntegrationTestManager finishes initialization, the animation is stopped by calling self.boot_animation.stop(), ensuring Pygame exits cleanly.
Join Threads: Ensure that animation_thread.join() is called to clean up resources used by Pygame once the animation is no longer needed.
Make sure to replace the checkbox names in self.checkbox_names with the actual names you need. Also, verify the path and naming of your boot images so that they load correctly.
import threading
import tkinter as tk
from tkinter import PhotoImage
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{i}.png')
img = Image.open(img_path)
img = img.resize((800, 600), Image.ANTIALIAS) # Resize to fit your Tkinter window if necessary
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
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Key Changes Made:
Loading Images: The method load_animation_images loads the images into a list using Pillow. Each image is resized to fit within your Tkinter window.
Label for Animation: A Label widget is created to hold the boot animation images.
Animation Logic: The update_animation method updates the image shown on the label at a specific interval (in milliseconds). This method is repeatedly called using root.after, allowing it to run within the main Tkinter loop.
Stopping the Animation: Once the IntegrationTestManager finishes initializing, the stop_boot_animation method is called, which stops the animation and clears the image on the label.
Dynamic Updates: The animation updates dynamically without requiring a separate window.
Ensure Image Assets Are Available:
Make sure you have the images named boot_frame_1.png, boot_frame_2.png, etc., in a directory named boot_images in the same folder as your script or change the path accordingly.
Finally, test this out with appropriate images to see the animation play within your existing Tkinter application seamlessly!
import threading
import tkinter as tk
from tkinter import PhotoImage
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{i}.png')
img = Image.open(img_path)
img = img.resize((800, 600), Image.LANCZOS) # Use Image.LANCZOS for high-quality resizing
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
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Key Adjustments:
Resizing Images: The use of Image.LANCZOS is now properly implemented for high-quality resizing of images.
Ensure Correct Paths: Make sure that the directory path for your images and the names of the images are correct so they can be loaded without errors.
With these changes, the code should run without the AttributeError related to ANTIALIAS, and it should display your boot animation correctly in the main Tkinter window.
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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
# Loading text
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24))
self.loading_label.pack(pady=20)
# Animation label
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{i}.png')
img = Image.open(img_path)
img = img.resize((800, 600), Image.LANCZOS) # Use Image.LANCZOS for high-quality resizing
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='') # Clear loading text after app initialization
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Key Adjustments:
Loading Text Label: A Label widget (self.loading_label) is created to show the text "App Loading." This label is given a font size of 24 for visibility and is positioned at the top of the window.
Display the Loading Text: The text is displayed as the boot animation runs.
Clear Text After Initialization: The loading message is cleared once the IntegrationTestManager has completed its initialization, providing a clearer user experience.
This modification should adequately inform users that the application is loading while showing the boot animation images in the same window. Adjust the font and positioning as needed to fit your design preferences!
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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
# Loading text
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24))
self.loading_label.pack(pady=20)
# Animation label
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{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((800, 600), Image.LANCZOS) # Resize for the display
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='') # Clear loading text after app initialization
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Explanation of Background Removal:
Image Conversion: The image is converted to "RGBA" to ensure that an alpha channel exists for transparency.
Identifying Background Color: The code iterates through the pixel data of the image and checks if the RGB values fall within a specified range (targeting light colors/shades typically used for background).
Setting Transparency: If a pixel matches the background color, it’s replaced with a transparent pixel (255, 255, 255, 0).
Resizing: The image is then resized to fit your application's display.
Note
Adjust the conditions in if item[0] in ... to better suit the specific background color of your images. If the background is not uniform or white, it may need another approach (like creating masks or using image editing software beforehand).
It's highly recommended to manually handle complex images using tools like Photoshop before using them in an application if the background removal needs are nuanced.
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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
# Loading text with specified foreground color
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24), fg="green")
self.loading_label.pack(pady=20)
# Animation label
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
self.create_checkbox_list()
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{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:
# Remove white background and make it transparent
if item[0] in list(range(200, 256)) and item[1] in list(range(200, 256)) and item[2] in list(range(200, 256)):
new_data.append((255, 255, 255, 0)) # Change white (and shades) to transparent
else:
new_data.append(item)
img.putdata(new_data)
img = img.resize((800, 600), Image.LANCZOS) # Resize for the display
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='') # Clear loading text after app initialization
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Customizing Text Color:
You can change the fg parameter value to any color you like. Here are a few examples:
Red Text: fg="red"
Blue Text: fg="blue"
Hexadecimal Color Code: fg="#FF5733" (an orange-like color, for example)
By adjusting the fg parameter, you can customize the text to match your application's theme or just to provide better visibility.
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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
# Loading text with specified foreground color
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24), fg="green")
self.loading_label.pack(pady=20)
# Animation label
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{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:
# Remove white background and make it transparent
if item[0] in list(range(200, 256)) and item[1] in list(range(200, 256)) and item[2] in list(range(200, 256)):
new_data.append((255, 255, 255, 0)) # Change white (and shades) to transparent
else:
new_data.append(item)
img.putdata(new_data)
img = img.resize((800, 600), Image.LANCZOS) # Resize for the display
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='') # Clear loading text after app initialization
self.create_checkbox_list() # Create checkbox list after boot animation stops
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Key Changes:
Deferred Checkbox Creation: The call to create_checkbox_list() is moved to the stop_boot_animation method. This ensures that the checkboxes are created only after the boot animation has stopped and the loading message has been cleared.
Initialization Flow: Now, the user will see "App Loading" with the animation, and once the loading is finished, the checkboxes will appear.
This update improves the user experience by clearly controlling when interface elements are displayed based on the application's internal state.
import threading
import tkinter as tk
from plyer import notification
from integration_test_manager import IntegrationTestManager
from PIL import Image, ImageTk
import os
class LaveUi:
def __init__(self, root):
self.init_event = None
self.checkbox_frame = None
self.root = root
self.test_handler = None
self.thread = None
self.init_handler = False
self.root.title("LAVU L2 Test Bench")
self.root.geometry("1080x800") # Set the size of the window
# 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
# Loading text with specified foreground color
self.loading_label = tk.Label(self.root, text="App Loading", font=("Helvetica", 24), fg="green")
self.loading_label.pack(pady=20)
# Animation label
self.animation_label = tk.Label(self.root)
self.animation_label.pack(pady=20)
# Entry for user input
self.user_input_label = tk.Label(self.root, text="Enter some text:")
self.user_input_label.pack(pady=10)
self.user_input = tk.Entry(self.root, font=("Helvetica", 16))
self.user_input.pack(pady=10)
self.submit_button = tk.Button(self.root, text="Submit", command=self.get_user_input)
self.submit_button.pack(pady=10)
# Start boot animation
self.load_animation_images()
self.start_boot_animation()
self.initTestManager() # Initialize Test Manager
def load_animation_images(self):
# Load your boot images
directory = "boot_images" # Make sure this folder contains the images
for i in range(1, 6): # Assuming you have 5 images named boot_frame_1.png to boot_frame_5.png
img_path = os.path.join(directory, f'boot_frame_{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:
# Remove white background and make it transparent
if item[0] in list(range(200, 256)) and item[1] in list(range(200, 256)) and item[2] in list(range(200, 256)):
new_data.append((255, 255, 255, 0)) # Change white (and shades) to transparent
else:
new_data.append(item)
img.putdata(new_data)
img = img.resize((800, 600), Image.LANCZOS) # Resize for the display
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='') # Clear loading text after app initialization
self.create_checkbox_list() # Create checkbox list after boot animation stops
def get_user_input(self):
# Get text from the Entry widget
input_text = self.user_input.get()
print("User input:", input_text) # You can do something with this text, like process it or display
def exit_button(self):
exit_button = tk.Button(self.root, text="Exit", command=self.root.quit)
exit_button.pack(pady=10) # Position at the bottom
@staticmethod
def show_toast():
notification.notify(
title='LAVU L2 Test Bench',
message='Test Application Not Properly Started..Wait !!',
app_name='My Application',
timeout=10 # Duration in seconds
)
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)
# 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)
def checkbox_toggled(self, index):
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.init_handler:
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 Progress..")
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="10.0.10.154", grpc_port="8866", dlt_port=3490, secure=False, init_event=self.init_event)
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_handler = True
# 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):
self.thread.join() # Wait for the test manager thread to finish
if __name__ == "__main__":
root = tk.Tk()
app = LaveUi(root)
app.exit_button()
root.mainloop()
Explanation of Key Components Added:
Entry Widget: The Entry widget (self.user_input) allows users to input text. It is displayed with a label prompting the user to enter text.
Submit Button: The submit_button triggers the get_user_input method when clicked.
get_user_input Method: This method retrieves the text from the Entry widget and prints it to the console (you can modify this to use the text as needed in your application).
Now, when you run the application, users will see the "Enter some text:" label and an input area where they can type their text. After clicking "Submit," the input will be printed to the console. You can modify this functionality to integrate the user input into your application logic as needed.