• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Movies

menator01

Silver Coder
Helping someone in another forum that is using idbm database calls and thought I would post the solution I came up with here, in case someone wants to take the project further
or perhaps use as a learning experience. Note: It takes a minute to get the results back as there are multiple queries involved.

Python:
# Do the imports
from imdb import Cinemagoer
import tkinter as tk
from tkinter import ttk
from urllib.request import urlopen
from PIL import ImageTk, Image
import io
class Database:
    def __init__(self):
        self.query = Cinemagoer()
    def search_person(self, name):
        return self.query.search_person(name.strip())[0]
    
    def get_person(self, id):
        return self.query.get_person(id.strip())
    
    def search_movie(self, name):
        return self.query.search_movie(name.strip())
    
    def get_movie(self, id):
        return self.query.get_movie(id.strip())
    
class Window:
    def __init__(self, parent):
        parent.columnconfigure(0, weight=1)
        parent.rowconfigure(0, weight=1)
        parent.minsize(1204, 768)
        parent.title('Movie Search')
        # Containers
        container = tk.Frame(parent, bg='#cecece')
        container.grid(column=0, row=0, sticky='news', padx=5, pady=5)
        container.grid_columnconfigure(0, weight=3)
        container.grid_rowconfigure(3, weight=3)
        # Header
        headerframe = tk.Frame(container, bg='#333333')
        headerframe['highlightbackground'] = '#000000'
        headerframe['highlightcolor'] = '#000000'
        headerframe['highlightthickness'] = 1
        headerframe.grid(column=0, row=0, sticky='new', pady=1)
        headerframe.grid_columnconfigure(0, weight=3)
        # Messages
        msgframe = tk.Frame(container, bg='#333333')
        msgframe['highlightbackground'] = '#000000'
        msgframe['highlightcolor'] = '#000000'
        msgframe['highlightthickness'] = 1
        msgframe.grid(column=0, row=1, sticky='new', pady=1)
        msgframe.grid_columnconfigure(1, weight=3)
        # Search Fields
        searchframe = tk.Frame(container, bg='#555555')
        searchframe.grid(column=0, row=2, sticky='new')
        for i in range(5):
            weight = 4 if i == 3 else 1
            searchframe.columnconfigure(i, weight=weight, uniform='cols')
        dataframe = tk.Frame(container,bg='#555555')
        dataframe.grid(column=0, row=3, sticky='news')
        dataframe.columnconfigure(0, weight=3, uniform='data')
        dataframe.columnconfigure(1, weight=3, uniform='data')
        dataframe.rowconfigure(0, weight=3)
        leftframe = tk.Frame(dataframe, bg='#555555')
        leftframe.grid(column=0, row=0, sticky='news', padx=2)
        leftframe.grid_columnconfigure(0, weight=3)
        leftframe.grid_rowconfigure(0, weight=3)
        
        rightframe = tk.Frame(dataframe, bg='white', padx=10, pady=10)
        rightframe.grid(column=1, row=0, sticky='news')
        rightframe.grid_columnconfigure(0, weight=3)
        rightframe.grid_rowconfigure(0, weight=3)
        footerframe = tk.Frame(container)
        footerframe.grid(column=0, row=4, sticky='new')
        # Label and field widgets
        label = tk.Label(headerframe, text='Movie Search')
        label['bg'] = '#555555'
        label['fg'] = '#ffffff'
        label['font'] = (None, 28, 'bold')
        label.grid(column=0, row=0, sticky='new', ipadx=10, ipady=5)
        label = tk.Label(msgframe, text='MSG: ', bg='#555555', fg='#ffffff')
        label['font'] = (None, 12, 'bold')
        label.grid(column=0, row=0, padx=2, pady=3, ipadx=3, ipady=3)
        self.msg = tk.Label(msgframe, anchor='w', bg='#555555', fg='cyan')
        self.msg['font'] = (None, 12, 'normal')
        self.msg.grid(column=1, row=0, sticky='new', padx=2, pady=3, ipadx=3, ipady=3)
        label = tk.Label(searchframe, text='Searchby:', bg='#555555', fg='#ffffff')
        label['font'] = (None, 12, 'bold')
        label.grid(column=0, row=0, padx=2, pady=4, sticky='new')
        options = ['Person', 'Movie']
        self.term = tk.StringVar()
        self.term.set(options[0])
        option = tk.OptionMenu(searchframe, self.term, *options)
        option['font'] = (None, 10, 'normal')
        option.grid(column=1, row=0, padx=2, sticky='new')
        label = tk.Label(searchframe, text='Search for:', bg='#555555', fg='#ffffff')
        label['font'] = (None, 12, 'bold')
        label.grid(column=2, row=0, padx=4, pady=4, sticky='new')
        self.entry = tk.Entry(searchframe)
        self.entry['font'] = (None, 12, 'normal')
        self.entry.grid(column=3, row=0, padx=4, pady=4, sticky='new')
        self.button = tk.Button(searchframe, text='Search', cursor='hand2')
        self.button.grid(column=4, row=0, padx=2, sticky='new')
 
        self.tree = ttk.Treeview(leftframe, selectmode='browse', show='headings', cursor='hand2')
        self.tree.grid(column=0, row=0, sticky='news')
        tree_scrollbar = tk.Scrollbar(leftframe, orient='vertical', command=self.tree.yview)
        self.tree.configure(yscrollcommand=tree_scrollbar.set)
        tree_scrollbar.configure(bg='#444444', activebackground='#666666', cursor='hand2')
        tree_scrollbar.grid(column=1, row=0, sticky='ns', padx=4)
        self.tree2 = tk.Text(rightframe, wrap=tk.WORD)
        self.tree2['highlightthickness'] = 0
        self.tree2['borderwidth'] = 0
        self.tree2['state'] = 'disabled'
        self.tree2.grid(column=0, row=0, sticky='news')
        tree2_scrollbar = tk.Scrollbar(rightframe, orient='vertical', command=self.tree2.yview)
        self.tree2.configure(yscrollcommand=tree2_scrollbar.set)
        tree2_scrollbar.configure(bg='#444444', activebackground='#666666', cursor='hand2')
        tree2_scrollbar.grid(column=1, row=0, sticky='ns', padx=4)
        footer = tk.Label(footerframe, text='mypython.org', bg='#333333', fg='#ffffff')
        footer['font'] = (None, 12, 'italic bold')
        footer['cursor'] = 'hand2'
        footer.pack(expand=True, fill='x', pady=5, ipady=3)

class Controller:
    def __init__(self, window, database):
        self.window = window
        self.database = database
        # Button Commands
        self.window.button['command'] = self.search
        self.window.entry.bind('<Return>', lambda event: self.search())
        # Clear trees
        self.window.term.trace('w', self.clear)
        # Bind treeview
        self.window.tree.bind('<<TreeviewSelect>>', self.details)     
    def clear(self, write, index, mode):
        self.window.entry.delete(0, 'end')
        self.window.tree.delete(*self.window.tree.get_children())
        self.window.tree2['state'] = 'normal'
        self.window.tree2.delete('1.0', 'end')
        self.window.tree2['state'] = 'disabled'
       
    def search(self):
            name = self.window.entry.get().strip()
            self.clear(None, None, None)
            self.window.tree.tag_configure('oddrow', background='#ccceee')
            self.window.tree.tag_configure('evenrow', background='#eeefff')
            if self.window.term.get() == 'Person':
                if name:
                    person = self.database.search_person(name)
                    data = self.get_person(person.personID)
                    data.sort()
                    self.window.tree['columns'] = ['title', 'id']
                    self.window.tree.column('title', minwidth=0, stretch='yes')
                    self.window.tree.column('id', minwidth=0, width=100, stretch='no')
                    self.window.tree.heading('title', text=f'Title\'s')
                    self.window.tree.heading('id', text=f'Movie ID')
                    for index, movie in enumerate(data):
                        if index % 2 == 0:
                            self.window.tree.insert('', 'end', values=(movie[0], movie[1],), tags=('oddrow',))
                        else:
                            self.window.tree.insert('', 'end', values=(movie[0],movie[1]), tags=('evenrow',))
            
            elif self.window.term.get() == 'Movie':
                if name:
                    data = self.database.search_movie(name)
                    
                    data.sort()
                    self.window.tree['columns'] = ['title', 'id']
                    self.window.tree.column('title', minwidth=0, stretch='yes')
                    self.window.tree.column('id', minwidth=0, width=100, stretch='no')
                    self.window.tree.heading('title', text=f'Title\'s')
                    self.window.tree.heading('id', text=f'Movie ID')
                    for index, movie in enumerate(data):
                        if index % 2 == 0:
                            self.window.tree.insert('', 'end', values=(movie.get('title'), movie.movieID,), tags=('oddrow',))
                        else:
                            self.window.tree.insert('', 'end', values=(movie.get('title'), movie.movieID,), tags=('evenrow',))
    def get_person(self, personid):
        person = self.database.get_person(personid)
        jobs = [job for job in person.get('filmography')]
        movies = [movie for movie in person['filmography'][jobs[0]]]
        titles = []
        for movie in movies:
            titles.append((movie.get('title'), movie.movieID))
        return titles
    
    def search_movie(self, name):
        return self.database.search_movie(name)
    
    def get_movie(self, movieid):
        return self.database.get_movie(str(movieid))
    def details(self, event):
        try:
            item = self.window.tree.focus()
            movieid = self.window.tree.item(item)['values'][1]
            data = self.get_movie(movieid)
        except IndexError:
            pass
        else:
            title = data.get('title')
            year = data.get('production status') if 'production status' in data.keys() else data.get('year')
            cover = data.get('full-size cover url')
            cast = [name.get('name') for name in data.get('cast')]
            plot_outline = data.get('plot outline')
            aired = data.get('original air date')
            rating = data.get('rating')
            img_url = urlopen(cover).read()
            img = Image.open(io.BytesIO(img_url))
            img = img.resize((300,400))
            image = ImageTk.PhotoImage(img)
            alist = [f'Title: {title}', 'img',
                     f'\n\nYear: {year}', f'Aired: {aired}',
                     f'Rating: {rating}', f'Plot Outline:\n{plot_outline}', f'Cast:\n{", ".join(cast)}']
            self.window.tree2['state'] = 'normal'
            self.window.tree2.delete('1.0', 'end')
            for index, data in enumerate(alist):
                    if data == 'img':
                        self.window.tree2.image_create('end', image=image)
                    else:
                        self.window.tree2.insert('end', f'{data}\n\n')
            self.window.tree2['state'] = 'disabled'
            image.bk=image

if __name__ == '__main__':
    root = tk.Tk()
    controller = Controller(Window(root), Database())
    img = urlopen('https://my-python.org/images/png/ratt.png')
    data = img.read()
    image = tk.PhotoImage(data=data)
    root.wm_iconphoto(True, image)
    root.mainloop()
 
Last edited:
A PyQt6 version (Still needs tweaks)
Python:
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout, QLabel,
                             QHBoxLayout, QVBoxLayout, QComboBox, QLineEdit, QPushButton,
                             QListWidget, QFrame, QScrollArea)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap, QImage
from imdb import Cinemagoer
import requests

class Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setMinimumWidth(1024)
        self.setMinimumHeight(840)
        self.showMaximized()

        app = QApplication.instance()
        screen = app.primaryScreen()
        geo = screen.availableGeometry()

        # Containers
        container = QGridLayout()
        search_grid = QHBoxLayout()
        midgrid = QHBoxLayout()

        # Header
        header = QLabel('Movie Search')
        header.setStyleSheet(
            'background-color: #555555;'
            'color: #fffeee;'
            'font-size: 50px;'
            'font-weight: bold'
            )
        header.setAlignment(Qt.AlignmentFlag.AlignCenter)


        # Search Grid labels and entry fields
        pre_searchby = QLabel('Search By:')
        pre_searchby.setStyleSheet(
            'padding: 0 10px 0 0;'
            'font-weight: bold'
        )
        self.what = QComboBox()
        self.what.addItems(['Person', 'Movie'])
        search_for = QLabel('Search For:')
        search_for.setStyleSheet(
            'padding: 10px 0 10px 0;'
            'font-weight: bold'
        )
        self.term = QLineEdit()
        self.term.setPlaceholderText('Search for a person\'s name')

        self.button = QPushButton('Search')

        # Listbox
        self.left = QListWidget()
        self.left.setMinimumWidth(500)
        self.left.setMaximumWidth(geo.width()//2)
        self.left.setSpacing(3)

        # Frame for data
        self.datagrid = QGridLayout()
        self.datagrid.setAlignment(Qt.AlignmentFlag.AlignTop)

        right = QFrame()
        right.setMinimumWidth(500)
        right.setMaximumWidth(geo.width()//2)
        right.setFrameStyle(6)
        right.setLayout(self.datagrid) 
        right.setStyleSheet('background-color: white;') 

        # Add to search layout
        search_grid.addWidget(pre_searchby)
        search_grid.addWidget(self.what)
        search_grid.addWidget(search_for)
        search_grid.addWidget(self.term)
        search_grid.addWidget(self.button)

        midgrid.addWidget(self.left)
        midgrid.addWidget(right)

        # Add to container
        container.addWidget(header, 0,0)
        container.addLayout(search_grid, 1, 0)
        container.addLayout(midgrid, 2, 0)

        widget = QWidget()
        widget.setLayout(container)
        self.setCentralWidget(widget)
        self.show()


class Data:
    def __init__(self):
        self.action = Cinemagoer()

    def search_person(self, name):
        return self.action.search_person(name.strip())
    
    def get_person(self, id):
        return self.action.get_person(id)
    
    def search_movie(self, name):
        return self.action.search_movie(name)
    
    def get_movie(self, movieid):
        return self.action.get_movie(movieid)


class Controller:
    def __init__(self, data, window):
        self.window = window
        self.data = data       

        # Button commands
        self.window.button.clicked.connect(self.search)

        # Place holder text
        self.window.what.currentTextChanged.connect(self.whatchange)

        # Detect if the return key was pressed
        self.window.term.returnPressed.connect(self.search)

        # List item was clicked
        self.window.left.itemClicked.connect(self.get_movie)

    def get_movie(self, movie):
        movieid = self.data.search_movie(movie.text())[0].movieID
        title = self.data.get_movie(movieid)
        self.display(title)

    def display(self, data):
        for i in reversed(range(self.window.datagrid.count())):
            self.window.datagrid.itemAt(i).widget().deleteLater()

        title = data.get('title')
        year = data.get('production status') if 'production status' in data.keys() else data.get('year')
        cast = [name.get('name') for name in data.get('cast')]
        cover = data.get('full-size cover url')
        plot = data.get('plot outline')
        rating = data.get('rating')

        scrollable = QScrollArea()
        

        # Header
        header = QLabel(title)
        header.setAlignment(Qt.AlignmentFlag.AlignCenter)
        header.setMaximumHeight(80)
        header.setStyleSheet('font-size: 25px; font-weight: bold; background-color: #555555; color: #eeefff; padding: 10px;')
        self.window.datagrid.addWidget(header, 0,0,1,4, Qt.AlignmentFlag.AlignTop)

        # Cover Image
        if cover != None:
            image = QImage()
            image.loadFromData(requests.get(cover).content)
            lb = QLabel()
            pixmap = QPixmap(image)
            lb.setPixmap(pixmap.scaled(300,300))
            self.window.datagrid.addWidget(lb, 1,0,3,1, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)

        common = 'font-weight: bold;'
        label = QLabel('Released:')
        label.setStyleSheet(common)

        self.window.datagrid.addWidget(label, 1, 1, 1, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
        self.window.datagrid.addWidget(QLabel(str(year)), 1, 2, 1, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)

        label = QLabel('Rating:')
        label.setStyleSheet(common)
        self.window.datagrid.addWidget(label, 2, 1, 1, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
        self.window.datagrid.addWidget(QLabel(str(rating)), 2, 2, 1, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)


        spacer = QFrame()
        self.window.datagrid.addWidget(spacer,1,3,3,1)

        self.window.datagrid.setColumnStretch(0,0)
        self.window.datagrid.setColumnStretch(1,0)
        self.window.datagrid.setColumnStretch(2,0)
        self.window.datagrid.setColumnStretch(3, 1)

        self.window.datagrid.addWidget(spacer,3,1,1,2)
        self.window.datagrid.setRowStretch(0, 0)
        self.window.datagrid.setRowStretch(1, 0)
        self.window.datagrid.setRowStretch(2, 0)
        self.window.datagrid.setRowStretch(3, 0)


        
        label = QLabel('Plot Outline:')
        label.setStyleSheet(common)

        self.window.datagrid.addWidget(label, 4, 0, 1, 5, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)

        text = QLabel(str(plot))
        text.setWordWrap(True)
        text.setStyleSheet('margin: 10px;')
        self.window.datagrid.addWidget(text, 5, 0, 1, 5, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
        self.window.datagrid.setRowStretch(4, 0)
        self.window.datagrid.setRowStretch(5, 2)

        label = QLabel('Cast:')
        label.setStyleSheet(common)
        
        text = QLabel(', '.join(cast))
        text.setWordWrap(True)
        text.setStyleSheet('margin: 10px;')
        self.window.datagrid.addWidget(label, 6, 0, 1, 5, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)

        self.window.datagrid.addWidget(text, 7, 0, 1, 5, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
        self.window.datagrid.setRowStretch(6, 0)
        self.window.datagrid.setRowStretch(7,2)

        self.window.datagrid.addWidget(spacer, 8, 0, 1, 4)
        self.window.datagrid.setRowStretch(8, 1)

        



        
        
                
        


    def whatchange(self):
        self.window.term.clear()
        if self.window.what.currentText() == 'Person':
            self.window.term.setPlaceholderText('Search for a person\'s name')
        elif self.window.what.currentText() == 'Movie':
            self.window.term.setPlaceholderText('Search for a movie title')
        
        self.window.left.clear()
        # self.window.right.clear()

    def search(self):
        self.window.left.clear()
        # self.window.right.clear()
        term = self.window.term.text()
        titles = []
        if term:
            self.window.term.clear()
            if self.window.what.currentText() == 'Person':
                personid = self.data.search_person(term)[0].personID
                person = self.data.get_person(personid)

                jobs = [job for job in person.get('filmography')]
                movies = [movie for movie in person['filmography'][jobs[0]]]
            
            elif self.window.what.currentText() == 'Movie':
                movies = self.data.search_movie(term)

            for movie in movies:
                    titles.append((movie.get('title'), movie.movieID))
                
            for title in titles:
                self.window.left.addItem(title[0])
                
        return False




if __name__ == '__main__':
    app = QApplication([])
    controller = Controller(Data(), Window())
    app.exec()
 

New Threads

Latest posts

Buy us a coffee!

300x250
Top Bottom