Home > Software engineering >  First time using Tkinter
First time using Tkinter

Time:01-30

I'm trying to turn this into a GUI program.

import random

select = input("This is a random movie picker. ----- FOR RANDOM -> TYPE 1 , FOR RANDOM BY FIRST LETTER -> TYPE 2 ")

if select == "1":
 randomize = print("Picking a movie...")
 with open("movies.txt") as f:
 lines = f.readlines()
 print (random.choice(lines))

elif select == "2":
 letter = input("Choose a letter: ")
 with open("movies.txt") as f:
 movies = f.readlines()
 filtered_movies = list(filter(lambda m: m[0].lower() == letter.lower(), movies))
 print(random.choice(filtered_movies))

else:
 print("The options are only 1 and 2.")

I tried this but I don't understand how am i supposed to make it choose a random line from a .txt file.

import random
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog

class MoviePicker:
 def __init__(self,root):
 self.root = root.
 self.root.title("Movie Picker")
 self.root.geometry("800x800")
 self.menubar = Menu(self.root)
 self.root.config(menu=self.menubar)
 self.r = Menu(self.menubar)
 self.r.add_command()
 self.fl = Menu(self.menubar)
 self.fl.add_command()

CodePudding user response:

Since you already had the algorithm, you basically have done everything.

I have written an example code using your algorithm:

from tkinter import *
import random

root = Tk()
root.title('Random Movie Picker')

# HEADER
welcomeFrame = Frame(root)
welcomeFrame.grid(row=3, column=3)

head_title = Label(welcomeFrame, text='RANDOM MOVIE PICKER', font=('Verdana', 12, 'bold'))
head_title.grid(row=3, column=3)

# FUNCTION
functionFrame = Frame(root)
functionFrame.grid(row=5, column=3)

Label(functionFrame).grid(row=1, column=3)
Label(functionFrame, text='Random Movie name:').grid(row=3, column=3)
Label(functionFrame, text='Random Movie by the first letter:').grid(row=5, column=3)
default_pickMovie = Button(functionFrame, text='Pick for me')
firstLetter_pickMovie = Button(functionFrame, text='Pick for me')

default_pickMovie.grid(row=4, column=3)
firstLetter_pickMovie.grid(row=6, column=3)


def pick1():
    movieWindow = Toplevel(root)
    movieWindow.title('Movie Picker')

    showProgress = Label(movieWindow, text="Picking a movie...")
    root.after(random.randint(1500, 3000),
               lambda: showProgress.configure(text=f'Your movie is: {random.choice(lines).strip()}'))
    showProgress.pack()
    with open("movies.txt") as f:
        lines = f.readlines()


def pick2():
    movieWindow = Toplevel(root)
    movieWindow.title('Movie Picker by the first letter')
    movieWindow.lift()

    showProgress = Label(movieWindow, text='Press any key to choose the letter...')
    showProgress.pack()

    def binding(events):
        letter = events.char
        with open("movies.txt") as f:
            movies = f.readlines()
        filtered_movies = list(filter(lambda m: m[0].lower() == letter.lower(), movies))
        chosenMovie = random.choice(filtered_movies).strip() if filtered_movies else False

        showProgress.configure(text="Picking a movie...")
        root.after(random.randint(1500, 3000),
                   lambda: showProgress.configure(
                       text=f'{f"Your movie is: {chosenMovie}" if chosenMovie else "Could not find any movies for you."}'))

    root.bind('<Key>', binding)
    movieWindow.bind('<Key>', binding)


default_pickMovie.configure(command=pick1)
firstLetter_pickMovie.configure(command=pick2)

mainloop()

Let's separate the code into some parts.


Import packages:

from tkinter import *
import random

Create the main window:

root = Tk()
root.title('Random Movie Picker')

Create the header/title for the main window:

welcomeFrame = Frame(root)
welcomeFrame.grid(row=3, column=3)

head_title = Label(welcomeFrame, text='RANDOM MOVIE PICKER', font=('Verdana', 12, 'bold'))
head_title.grid(row=3, column=3)

Note: The reason I grid the welcomeFrame frame and the head_title label in row=3, column=3 is to make sure that I can still add more widgets in the previous row and column (Example: row=2, column=1).

Create buttons for 2 options:

functionFrame = Frame(root)
functionFrame.grid(row=5, column=3)

Label(functionFrame).grid(row=1, column=3)
Label(functionFrame, text='Random Movie name:').grid(row=3, column=3)
Label(functionFrame, text='Random Movie by the first letter:').grid(row=5, column=3)
default_pickMovie = Button(functionFrame, text='Pick for me')
firstLetter_pickMovie = Button(functionFrame, text='Pick for me')

default_pickMovie.grid(row=4, column=3)
firstLetter_pickMovie.grid(row=6, column=3)

Create function to choose a random movie from a file:

def pick1():
    movieWindow = Toplevel(root)
    movieWindow.title('Movie Picker')

    showProgress = Label(movieWindow, text="Picking a movie...")
    root.after(random.randint(1500, 3000),
               lambda: showProgress.configure(text=f'Your movie is: {random.choice(lines).strip()}'))
    showProgress.pack()
    with open("movies.txt") as f:
        lines = f.readlines()

Create a function to pick a random movie by a letter:

def pick2():
    movieWindow = Toplevel(root)
    movieWindow.title('Movie Picker by the first letter')
    movieWindow.lift()

    showProgress = Label(movieWindow, text='Press any key to choose the letter...')
    showProgress.pack()

    def binding(events):
        letter = events.char
        with open("movies.txt") as f:
            movies = f.readlines()
        filtered_movies = list(filter(lambda m: m[0].lower() == letter.lower(), movies))
        chosenMovie = random.choice(filtered_movies).strip() if filtered_movies else False

        showProgress.configure(text="Picking a movie...")
        root.after(random.randint(1500, 3000),
                   lambda: showProgress.configure(
                       text=f'{f"Your movie is: {chosenMovie}" if chosenMovie else "Could not find any movies for you."}'))

    root.bind('<Key>', binding)
    movieWindow.bind('<Key>', binding)

Note: In this code, you need to press a key in your keyboard and it will automatically pick a movie by that key.

Connect the 2 functions with the buttons:

default_pickMovie.configure(command=pick1)
firstLetter_pickMovie.configure(command=pick2)

Then add mainloop() to prevent Tkinter from closing after running all the code:

mainloop()

This is my movies.txt file (It's just an example, you can change whatever you want):

The Lord of the Rings: The Two Towers (2002)
Inception (2010)
Star Wars: Episode V - The Empire Strikes Back (1980)
The Matrix (1999)
The Silence of the Lambs (1991)
Interstellar (2014)
The Pianist (2002)
Spirited Away (2001)
Terminator 2: Judgment Day (1991)
Star Wars: Episode IV - A New Hope (1977)
The Lion King (1994)
Toy Story (1995)
Avengers: Endgame (2019)
Toy Story 3 (2010)
Star Wars: Episode VI - Return of the Jedi (1983)
Finding Nemo (2003)
Hacksaw Ridge (2016)
How to Train Your Dragon (2010)
Monsters, Inc. (2001)
The Terminator (1984)

The result:

Main Window


Random Movie


Random Movie by the first letter


But, there are a few problems with this code like:
  • In the random movie by first letter option, when you press a key and it has picked a movie for you, if you press an another key, it will pick again, which is quite annoying.
  • Ugly GUI (You can use CustomTkinter for better GUI Design).

  • Related