Advertisement
Guest User

Scrollable Text Box

a guest
Mar 5th, 2025
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. import pygame
  2. import pygame_gui
  3.  
  4. # Initialize Pygame
  5. pygame.init()
  6.  
  7. # Set up the window
  8. window_size = (800, 600)
  9. window_surface = pygame.display.set_mode(window_size)
  10. pygame.display.set_caption("Scrollable Text Box Example")
  11.  
  12. # Initialize UIManager
  13. manager = pygame_gui.UIManager(window_size)
  14.  
  15. # Define the text box rectangle (position and size)
  16. text_box_rect = pygame.Rect(100, 100, 400, 300)
  17.  
  18. # Create the text box with initial empty content
  19. text_box = pygame_gui.elements.UITextBox(
  20.     html_text="",
  21.     relative_rect=text_box_rect,
  22.     manager=manager
  23. )
  24.  
  25. # Store text content as a list of lines
  26. text_content = []
  27.  
  28.  
  29. def append_text(new_text):
  30.     text_content.append(new_text)
  31.     # Join lines with <br> for HTML line breaks
  32.     html_text = "<br>".join(text_content)
  33.     text_box.html_text = html_text
  34.     text_box.rebuild()  # Rebuild to update the text
  35.  
  36.     # Auto-scroll to the bottom
  37.     if text_box.vertical_scroll_bar:
  38.         # Set scroll position to the maximum
  39.         text_box.vertical_scroll_bar.scroll_position = (
  40.             text_box.vertical_scroll_bar.scrollable_height
  41.         )
  42.  
  43.  
  44. clock = pygame.time.Clock()
  45. is_running = True
  46.  
  47. while is_running:
  48.     time_delta = clock.tick(60) / 1000.0  # Limit to 60 FPS
  49.  
  50.     # Event handling
  51.     for event in pygame.event.get():
  52.         if event.type == pygame.QUIT:
  53.             is_running = False
  54.  
  55.         # Pass events to pygame_gui
  56.         manager.process_events(event)
  57.  
  58.         # Example: Append text when Enter is pressed
  59.         if event.type == pygame.KEYDOWN:
  60.             if event.key == pygame.K_RETURN:
  61.                 append_text("New message at the bottom!")
  62.  
  63.     # Update UI
  64.     manager.update(time_delta)
  65.  
  66.     # Draw the UI
  67.     window_surface.fill((255, 255, 255))  # White background
  68.     manager.draw_ui(window_surface)
  69.     pygame.display.update()
  70.  
  71. pygame.quit()
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement