I must show a photo after selecting name of airline in my tkinter app but after selecting the program becomes fully empty white screen

106 Views Asked by At

I have an Tkinter app, it must contain combobox with name of airlines, some text boxes (for showing description) and photo (image) but it doesn't work. I must contain everything in database (SQLite)

import tkinter as tk
from tkinter import ttk
import sqlite3
from PIL import Image, ImageTk
import os

class AviationApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Aviation Information")
        self.root.geometry("600x400")  # Устанавливаем начальные размеры окна

        # Используем полный путь к базе данных
        db_path = os.path.join(os.path.dirname(__file__), "aviation.db")
        self.conn = sqlite3.connect(db_path)

        # Принудительно пересоздаем таблицу при каждом запуске
        self.create_table()

        # Создаем интерфейс
        self.create_gui()

    def create_table(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS airlines (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT NOT NULL,
                    image_path TEXT NOT NULL,
                )
            """)
            self.conn.commit()
        except Exception as e:
            print(f"Error creating table: {e}")

    def create_gui(self):
        # Создаем комбобокс
        self.airline_var = tk.StringVar()
        self.airline_combobox = ttk.Combobox(self.root, textvariable=self.airline_var)
        self.airline_combobox.grid(row=0, column=0, padx=10, pady=10)
        self.airline_combobox.bind("<<ComboboxSelected>>", self.show_airline_info)

        # Загружаем данные из базы данных в комбобокс
        self.load_airlines()

        # Создаем метку для отображения описания
        self.description_label = tk.Label(self.root, text="")
        self.description_label.grid(row=1, column=0, padx=10, pady=10)

        # Создаем метку для отображения изображения 
        self.image_label = tk.Label(self.root)
        self.image_label.grid(row=2, column=0, padx=10, pady=10)

    def load_airlines(self):
        try:
            cursor = self.conn.cursor()

            # Выведем все таблицы в консоль
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
            tables = [row[0] for row in cursor.fetchall()]
            print(f"All tables: {tables}")

            # Выведем значения из таблицы
            cursor.execute("SELECT name FROM airlines")
            airlines = [row[0] for row in cursor.fetchall()]
            self.airline_combobox['values'] = sorted(airlines, key=lambda x: x.lower())
            print(f"Loaded airlines: {airlines}")
        except Exception as e:
            print(f"Error loading airlines: {e}")

    def show_airline_info(self, event):
        try:
            selected_airline = self.airline_var.get()
            cursor = self.conn.cursor()
            cursor.execute("SELECT description, image_path FROM airlines WHERE name=?", (selected_airline,))
            result = cursor.fetchone()

            if result:
                description, image_path = result
                self.description_label.config(text=description)

                # Отображаем изображение
                image = Image.open(image_path)
                photo = ImageTk.PhotoImage(image)

                # Установка размеров метки
                self.image_label.config(image=photo)
                self.image_label.image = photo
            else:
                self.description_label.config(text="")
                self.image_label.config(image=None)
        except Exception as e:
            print(f"Error showing airline info: {e}")

if __name__ == "__main__":
    root = tk.Tk()
    app = AviationApp(root)
    root.mainloop()

CREATE TABLE IF NOT EXISTS airlines (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT NOT NULL,
    image_path TEXT NOT NULL
);

In this way I'm storing the path to photo as :

C:/Users/danil/Downloads/American-Airlines-Logo.png

I tried to store as byte array, as image itself, as path to image, nothing worked.

1

There are 1 best solutions below

1
On

It works with your code itself after removing the comma (,) in the line-31 after image_path TEXT NOT NULL.

    def create_table(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS airlines (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT NOT NULL,
                    image_path TEXT NOT NULL
                )
            """)

Just for the sake of checking I just added the following line with a dummy image:

cursor.execute("""
            INSERT INTO airlines VALUES(25146, "American Airlines", "flight", "/home/muthu/Downloads/ailogo.png")
        """)

The Output : Screen Shot