Python Forum
General Coding - Bingo Generator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
General Coding - Bingo Generator
#1
Photo 
I work at a senior nursing home. All we do is play Bingo. I have used every app to call numbers. The residents are complaining that the same numbers are being called.

I downloaded Python the latest version.

Gave it the code to use and it pulls up the tinktn window. But when I push the "Call Numbers button" nothing happens. See pic.

I have never even heard of python before today. Using AI.

Is something wrong in this coding?

import random
import tkinter as tk

# Generate a list of all Bingo numbers
bingo_numbers = (
    ["B" + str(i) for i in range(1, 16)] +
    ["I" + str(i) for i in range(16, 31)] +
    ["N" + str(i) for i in range(31, 46)] +
    ["G" + str(i) for i in range(46, 61)] +
    ["O" + str(i) for i in range(61, 76)]
)

# Shuffle the Bingo numbers randomly
random.shuffle(bingo_numbers)

# Create the main window using Tkinter
root = tk.Tk()
root.title("Bingo Caller")
root.geometry("400x300")  # Set the window size

# Create a label to display the Bingo number
label = tk.Label(root, text="Press 'Call Number' to start", font=("Helvetica", 18))
label.pack(pady=20)

# Function to call the next Bingo number
def call_number():
    print("Button clicked!")  # Debugging line to ensure the function is called
    if bingo_numbers:  # Check if there are numbers left to call
        number = bingo_numbers.pop(0)
        label.config(text=number)
        print(f"Called number: {number}")  # Debugging line to check if a number is being popped
    else:  # If all numbers have been called
        label.config(text="All numbers called!")
        print("All numbers have been called.")  # Debugging line

# Create a button to call the next number
button = tk.Button(root, text="Call Number", command=call_number, font=("Helvetica", 16))
button.pack(pady=20)

# Run the Tkinter main loop
root.mainloop()
deanhystad write Nov-04-2024, 03:48 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Attached Files

Thumbnail(s)
   
Reply
#2
Can you post a screenshot without maximizing the Bingo Caller window? I don't know what is going on with your program. When I run the posted code I get a fairly small window with a "Call Number" button centered slightly below the "Press 'Call Number' to start" text. When I press the button it replaces the "Press 'Call Number' to start" text with the called number ("B13" for example). How are you running the program, do you double click on the .py file or do you run it from the command line like python bingocaller.py?

Repeated sequences should not be a problem. I ran your code 1,000,000 times and the number sequence didn't repeat once. This is not surprising as the number of possible bingo sequences is huge. The number of ways you can randomly draw 72 bingo balls is 72! / (72 - 24)! = 4.9327271416e+42. I would have to run my test program billions of times to have any possibility of finding a repeating sequence of numbers. It is very, very, very unlikely that your program is generating two bingo games that are the same.

It is not unlikely that sequences of numbers will repeat. When I play 100 bingo games and compare the sequences of balls drawn it is not uncommon to see sequences of 2 or 3 balls that appear in two different games. A player might remember B13, N35, G50 and think the balls are falling in the same order, not remembering that this was 5 calls into one game and 15 calls into another. They may also remember N35, B13, G50 as being called in a previous game and think that is a match. Our minds are programmed to find patterns.

I added displays to show the called numbers. A list of the numbers displayed in the order called, and a sorted list of called numbers for each letter. I've called bingo and know how important it is to have accurate records.
import random
import tkinter as tk


class BingoLetter(tk.Label):
    """Display called numbers for a letter."""

    def __init__(self, parent, letter, **kwargs):
        super().__init__(parent, text="", anchor="w", **kwargs)
        self.letter = letter
        self.numbers = []
        self.update_text()

    def clear(self):
        """Clear the called numbers."""
        self.numbers.clear()
        self.update_text()

    def add_number(self, number):
        """Add number to the label."""
        self.numbers.append(int(number[1:]))
        self.update_text()

    def update_text(self):
        """Update label text to show called numbers."""
        self.config(text=f"{self.letter}: {str(sorted(self.numbers))[1:-1]}")


class Bingo(tk.Tk):
    """Window for calling bingo numbers."""

    all_numbers = (
        ["B" + str(i) for i in range(1, 16)]
        + ["I" + str(i) for i in range(16, 31)]
        + ["N" + str(i) for i in range(31, 46)]
        + ["G" + str(i) for i in range(46, 61)]
        + ["O" + str(i) for i in range(61, 76)]
    )

    def __init__(self):
        super().__init__()
        self.title("Bingo Caller")
        self.bingo_numbers = []
        self.last_number = tk.Label(self, text="Press 'Call Number' to start", font=("Helvetica", 18))
        self.called_numbers = tk.Text(self, width=50, height=7, wrap=tk.WORD, font=("Courier", 16))
        self.letters = {
            "B": BingoLetter(self, "B", font=("Courier", 12)),
            "I": BingoLetter(self, "I", font=("Courier", 12)),
            "N": BingoLetter(self, "N", font=("Courier", 12)),
            "G": BingoLetter(self, "G", font=("Courier", 12)),
            "O": BingoLetter(self, "O", font=("Courier", 12)),
        }
        buttons = tk.Frame(self)
        self.call_button = tk.Button(buttons, text="Call Number", command=self.call_number, font=("Helvetica", 18))
        self.restart_button = tk.Button(buttons, text="New Game", command=self.new_game, font=("Helvetica", 18))

        self.last_number.pack(side="top", padx=10, pady=(10, 0))
        self.called_numbers.pack(side="top", padx=10, pady=10)
        for letter in self.letters.values():
            letter.pack(side="top", padx=10, expand=True, fill=tk.X)
        buttons.pack(side="top", padx=10, pady=10)
        self.call_button.pack(side="left")
        self.restart_button.pack(side="left", padx=(10, 0))
        self.new_game()

    def call_number(self):
        """Called when "Call Number" button is pressed."""
        if self.bingo_numbers:
            # Get next number and update displays.
            number = self.bingo_numbers.pop()
            self.last_number.config(text=number)
            self.called_numbers.insert(tk.END, f"{number: <3} ")
            self.letters[number[0]].add_number(number)
        else:
            # No more numbers.  Notify user.
            self.last_number.config(text="All numbers have been called.")
            self.call_button.config(state="disabled")

    def new_game(self):
        """Start a new game."""
        self.last_number.config(text="Press 'Call Number' to start")
        self.bingo_numbers = random.sample(self.all_numbers, len(self.all_numbers))
        self.called_numbers.delete(1.0, tk.END)
        for letter in self.letters.values():
            letter.clear()
        self.call_button.config(state="normal")


Bingo().mainloop()
Reply
#3
I was intrigued by your project and thought I would give it a spin as well. This is what I have as of now.
Problem - getting the row number from the bingo card for comparison.

Todo:
  • Detect when there is a bingo
  • End game when there is a bingo
  • Create button to reset game
  • Grab all highlighted squares
  • Group highlighted squares by columns and rows
  • Group highlighted squares by diagonals


Updated code by the strike through on todo
Any help on getting diagonals would be great.


Finished. A working bingo game in tkinter.
Code could be optimized a little. Especially the part at getting the diagonals. (Lots of if)

import tkinter as tk
from random import choice, choices
from itertools import groupby

class Window():
    def __init__(self, parent):
        parent.columnconfigure(0, weight=1)
        parent.rowconfigure(0, weight=0)
        parent.rowconfigure(1, weight=1)
        parent.configure(padx=5, pady=5)
        self.parent = parent

        self.letters = ['B','I','N','G','O'] 

        header_frame = tk.Frame(parent)
        header_frame.grid(column=0, row=0, sticky='new')
        for index in range(len(self.letters)):
            header_frame.grid_columnconfigure(index, weight=3, uniform='header')
        
        
        for index, letter in enumerate(self.letters):
            header = tk.Label(header_frame, text=letter, bg='#0000ff', fg='#ffffff')
            header.grid(column=index, row=0, sticky='new', padx=1, pady=1)
            header.configure(font=(None, 50, 'bold'))


        self.card = tk.Frame(parent)
        self.card.grid(column=0, row=1, sticky='news')
        
        for index in range(len(self.letters)):
            self.card.grid_columnconfigure(index, weight=3, uniform='columns')
            self.card.grid_rowconfigure(index, weight=3, uniform='rows')
            
        self.labels = []
        index = 0
        for col in range(5):
            for row in range(5):
                label = tk.Label(self.card)
                label.configure(
                    highlightbackground = '#000000',
                    highlightcolor = '#000000',
                    highlightthickness = 1,
                    font = (None, 30, 'normal')
                )
                self.labels.append(label)
                self.labels[index].grid(column=col, row=row, sticky='news', padx=0.5, pady=0.5)
                index += 1

        self.label = tk.Label(parent, text='Messages:', anchor='w', padx=10)
        self.label.grid(column=0, row=2, sticky='new', padx=2, pady=4)
        self.label.configure(font=(None, 18, 'normal'),
                            highlightbackground = '#555555',
                            highlightcolor = '#555555',
                            highlightthickness = 1)

        btnframe = tk.Frame(parent)
        btnframe.grid(column=0, row=3, sticky='news', pady=5)
        btnframe.grid_columnconfigure(0, weight=3, uniform='button')
        btnframe.grid_columnconfigure(1, weight=3, uniform='button')

        self.drawbtn = tk.Button(btnframe, text='Draw', cursor='hand1', font=(None, 16, 'normal'))
        self.drawbtn.grid(column=0, row=3, pady=10)

        self.closebtn = tk.Button(btnframe, text='Exit', command=parent.destroy, cursor='hand1', font=(None, 16, 'normal'))
        self.closebtn.grid(column=1, row=3, padx=5, pady=5)
        self.closebtn.configure(activebackground='#ff0000', activeforeground='#ffffff', bg='tomato')


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

        # Our list of bingo numbers - North American bingo uses 75 numbers
        self.bingo_numbers = [f'{letter}{number}' for number in range(1,76) for letter in self.window.letters]
        self.bingo_numbers_copy = self.bingo_numbers[:]
        
        # Group by letter
        self.grouped_numbers = {}
        for word in self.bingo_numbers:
            self.grouped_numbers.setdefault(word[0], []).append(word)
        self.grouped_numbers = list(self.grouped_numbers.values())

        # Get 5 from each list
        card_nums = []
        for index, item in enumerate(self.grouped_numbers):
            card_nums.append(choices(self.grouped_numbers[index], k=5))

        # List to hold bingo card numbers
        self.card = []
        for items in card_nums:
            for item in items:
                self.card.append(item)
                        
        # Bind the draw button to draw meyhod
        self.window.drawbtn.configure(command=self.draw)

        # Populate the bingo card
        self.populate()

    def populate(self):
        ''' Method for populating the bingo card '''
        for index, label in enumerate(self.window.labels):
            if len(self.card) > 0:
                choose = self.card.pop(0)
            if self.window.labels[index].grid_info().get('column') == 2 and self.window.labels[index].grid_info().get('row') == 2:
                self.window.labels[index].configure(text='Free Space', bg='skyblue', font=(None, 18, 'bold'), wraplength=100)
            else:
                self.window.labels[index].configure(text=choose[1:], bg='#ffffff')

    def draw(self):
        ''' Method for drawing a random item from bingo numbers '''
        choose = choice(self.bingo_numbers_copy)

        # Remove item from list so not drawn again
        self.bingo_numbers_copy.remove(choose)

        # Display drawn number
        self.window.label.configure(text=f'Messages: ( {choose} ) was drawn')

        # Do the comparison
        self.compare(choose)

        self.check()

    def compare(self, choose):
        ''' Method for comparing drawn number with card numbers
            Highlights background of matched numbers '''

        # Need this for column numbers    
        header = list('BINGO')
        # Grab the letter and text of drawn number
        letter, number = choose[:1], choose[1:]
        # Convert number to int
        number = int(number)
    
        # Loop through the card and get some info
        for index, item in enumerate(self.window.labels):

            # Get the text of the label
            text = self.window.labels[index].cget('text')

            # Get the column of the label
            column = self.window.labels[index].grid_info().get('column')

            # Compare text and column number to drawn number and column
            # Highlight background
            try:
                if int(text) == number and header[column] == letter:
                    self.window.labels[index].configure(bg='skyblue')
            except ValueError:
                pass
            
    def check(self):
        # List of possible bingo
        bingo = [
                    [(i,0) for i in range(5)],
                    [(i,1) for i in range(5)],
                    [(i,2) for i in range(5)],
                    [(i,3) for i in range(5)],
                    [(i,4) for i in range(5)],
                    [(0,i) for i in range(5)],
                    [(1,i) for i in range(5)],
                    [(2,i) for i in range(5)],
                    [(3,i) for i in range(5)],
                    [(4,i) for i in range(5)],
                    [(0,0),(1,1),(2,2),(3,3),(4,4)],
                    [(0,4),(1,3),(2,2),(3,1),(4,0)]
                ]

        # Define some groups
        groups = []
        column_groups = {}
        row_groups = {}
        diag_groups = {}
        
        # Grab all highlighted squares and add to group
        squares = self.window.labels
        for index, square in enumerate(squares):
            cols = squares[index].grid_info().get('column')
            rows = squares[index].grid_info().get('row')
            if squares[index]['bg'] == 'skyblue':
                groups.append((cols, rows))

        # Group all highlighted squares by column
        for sublist in groups:
            key = sublist[0]
            value = (sublist[0], sublist[1])
            if key not in column_groups:
                column_groups[key] = []
            column_groups[key].append(value)
        column_groups = list(column_groups.values())

        # Sort for human readibility
        column_groups = sorted(column_groups)

        # Group all highlighted squares by rows
        for sublist in groups:
            key = sublist[1]
            value = (sublist[1], sublist[0])
            if key not in row_groups:
                row_groups[key] = []
            row_groups[key].append(value)
        row_groups = list(row_groups.values())

        # Sorted for human readibility
        row_groups = sorted(row_groups)

        diag1 = []
        diag2 = []
        for group in groups:
            col, row = group
            if col == 0 and row == 0:        
                diag1.append((col,row))
            if col == 1 and row == 1:        
                diag1.append((col,row))
            if col == 2 and row == 2:        
                diag1.append((col,row))
            if col == 3 and row == 3:        
                diag1.append((col,row))
            if col == 4 and row == 4:        
                diag1.append((col,row))

            if col == 0 and row == 4:        
                diag2.append((col,row))
            if col == 1 and row == 3:        
                diag2.append((col,row))
            if col == 2 and row == 2:        
                diag2.append((col,row))
            if col == 3 and row == 1:        
                diag2.append((col,row))
            if col == 4 and row == 0:        
                diag2.append((col,row))

        diags = [diag1, diag2]
        allgroups = [diags, column_groups, row_groups]

        for groups in allgroups:
            for group in groups:
                if group in bingo:
                    self.window.drawbtn.configure(command=self.reset, text='Reset')
                    self.window.label.configure(text=f'Messages: Bingo!')
            
    def reset(self):
        self.window.drawbtn.configure(command=self.draw, text='Draw')
        self.window.label.configure(text='Messages')
        self.bingo_numbers_copy = self.bingo_numbers[:]

        # Get 5 from each list
        card_nums = []
        for index, item in enumerate(self.grouped_numbers):
            card_nums.append(choices(self.grouped_numbers[index], k=5))

        # List to hold bingo card numbers
        self.card = []
        for items in card_nums:
            for item in items:
                self.card.append(item)
        self.populate()
        

if __name__ == '__main__':
    root = tk.Tk()
    root.title('BINGO')
    root.geometry('500x600')
    controller = Controller(Window(root))
    root.mainloop()

Attached Files

Thumbnail(s)
   
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#4
You are amazing. This is the exact information I needed to know what you said right here. I ran your code 1,000,000 times and the number sequence didn't repeat once. Sometimes we play 200 games a week. I feel like they are just hearing the same numbers because we play so often.

I was able to get the program to work by saving a file on my computer and it opens it up on a window on my computer. I was so excited.

So it works perfectly. However, the only problem is that i need those numbers like in the screen shot to be way larger so the older residents can see them. When I mess with the code it will not make the numbers bigger. Does this make sense?

I am so grateful for your reply. Are you able to help me make those numbers larger? Even when I press CTRL + the screen doesn't get larger.

Thank you so very much. I hope you can see this because it looks like I'm writing on top of what you sent over.




(Nov-04-2024, 09:57 PM)deanhystad Wrote: Can you post a screenshot without maximizing the Bingo Caller window? I don't know what is going on with your program. When I run the posted code I get a fairly small window with a "Call Number" button centered slightly below the "Press 'Call Number' to start" text. When I press the button it replaces the "Press 'Call Number' to start" text with the called number ("B13" for example). How are you running the program, do you double click on the .py file or do you run it from the command line like python bingocaller.py?

Repeated sequences should not be a problem. I ran your code 1,000,000 times and the number sequence didn't repeat once. This is not surprising as the number of possible bingo sequences is huge. The number of ways you can randomly draw 72 bingo balls is 72! / (72 - 24)! = 4.9327271416e+42. I would have to run my test program billions of times to have any possibility of finding a repeating sequence of numbers. It is very, very, very unlikely that your program is generating two bingo games that are the same.

It is not unlikely that sequences of numbers will repeat. When I play 100 bingo games and compare the sequences of balls drawn it is not uncommon to see sequences of 2 or 3 balls that appear in two different games. A player might remember B13, N35, G50 and think the balls are falling in the same order, not remembering that this was 5 calls into one game and 15 calls into another. They may also remember N35, B13, G50 as being called in a previous game and think that is a match. Our minds are programmed to find patterns.

I added displays to show the called numbers. A list of the numbers displayed in the order called, and a sorted list of called numbers for each letter. I've called bingo and know how important it is to have accurate records.
import random
import tkinter as tk


class BingoLetter(tk.Label):
    """Display called numbers for a letter."""

    def __init__(self, parent, letter, **kwargs):
        super().__init__(parent, text="", anchor="w", **kwargs)
        self.letter = letter
        self.numbers = []
        self.update_text()

    def clear(self):
        """Clear the called numbers."""
        self.numbers.clear()
        self.update_text()

    def add_number(self, number):
        """Add number to the label."""
        self.numbers.append(int(number[1:]))
        self.update_text()

    def update_text(self):
        """Update label text to show called numbers."""
        self.config(text=f"{self.letter}: {str(sorted(self.numbers))[1:-1]}")


class Bingo(tk.Tk):
    """Window for calling bingo numbers."""

    all_numbers = (
        ["B" + str(i) for i in range(1, 16)]
        + ["I" + str(i) for i in range(16, 31)]
        + ["N" + str(i) for i in range(31, 46)]
        + ["G" + str(i) for i in range(46, 61)]
        + ["O" + str(i) for i in range(61, 76)]
    )

    def __init__(self):
        super().__init__()
        self.title("Bingo Caller")
        self.bingo_numbers = []
        self.last_number = tk.Label(self, text="Press 'Call Number' to start", font=("Helvetica", 18))
        self.called_numbers = tk.Text(self, width=50, height=7, wrap=tk.WORD, font=("Courier", 16))
        self.letters = {
            "B": BingoLetter(self, "B", font=("Courier", 12)),
            "I": BingoLetter(self, "I", font=("Courier", 12)),
            "N": BingoLetter(self, "N", font=("Courier", 12)),
            "G": BingoLetter(self, "G", font=("Courier", 12)),
            "O": BingoLetter(self, "O", font=("Courier", 12)),
        }
        buttons = tk.Frame(self)
        self.call_button = tk.Button(buttons, text="Call Number", command=self.call_number, font=("Helvetica", 18))
        self.restart_button = tk.Button(buttons, text="New Game", command=self.new_game, font=("Helvetica", 18))

        self.last_number.pack(side="top", padx=10, pady=(10, 0))
        self.called_numbers.pack(side="top", padx=10, pady=10)
        for letter in self.letters.values():
            letter.pack(side="top", padx=10, expand=True, fill=tk.X)
        buttons.pack(side="top", padx=10, pady=10)
        self.call_button.pack(side="left")
        self.restart_button.pack(side="left", padx=(10, 0))
        self.new_game()

    def call_number(self):
        """Called when "Call Number" button is pressed."""
        if self.bingo_numbers:
            # Get next number and update displays.
            number = self.bingo_numbers.pop()
            self.last_number.config(text=number)
            self.called_numbers.insert(tk.END, f"{number: <3} ")
            self.letters[number[0]].add_number(number)
        else:
            # No more numbers.  Notify user.
            self.last_number.config(text="All numbers have been called.")
            self.call_button.config(state="disabled")

    def new_game(self):
        """Start a new game."""
        self.last_number.config(text="Press 'Call Number' to start")
        self.bingo_numbers = random.sample(self.all_numbers, len(self.all_numbers))
        self.called_numbers.delete(1.0, tk.END)
        for letter in self.letters.values():
            letter.clear()
        self.call_button.config(state="normal")


Bingo().mainloop()

Attached Files

Thumbnail(s)
   
Reply
#5
Add a font setting in this line in the call_number function
self.last_number.config(text=number)
Add this
self.last_number.config(text=number, font= ("Courier", 128))
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#6
Thank you so much. So this is my coding. Where can I put that line of coding in this coding so the numbers will be superlarge like attached picture? You said to add this to the coding.

Add a font setting in this line in the call_number function
self.last_number.config(text=number)
Add this
self.last_number.config(text=number, font= ("Courier", 128))

import random
import tkinter as tk

# Generate a list of all Bingo numbers
bingo_numbers = (
    ["B" + str(i) for i in range(1, 16)] +
    ["I" + str(i) for i in range(16, 31)] +
    ["N" + str(i) for i in range(31, 46)] +
    ["G" + str(i) for i in range(46, 61)] +
    ["O" + str(i) for i in range(61, 76)]
)

# Shuffle the Bingo numbers randomly
random.shuffle(bingo_numbers)

# Create the main window using Tkinter
root = tk.Tk()
root.title("Bingo Caller")
root.geometry("400x300")  # Set the window size

# Create a label to display the Bingo number
label = tk.Label(root, text="Press 'Call Number' to start", font=("Helvetica", 100))
label.pack(pady=20)

# Function to call the next Bingo number
def call_number():
    print("Button clicked!")  # Debugging line to ensure the function is called
    if bingo_numbers:  # Check if there are numbers left to call
        number = bingo_numbers.pop(0)
        label.config(text=number)
        print(f"Called number: {number}")  # Debugging line to check if a number is being popped
    else:  # If all numbers have been called
        label.config(text="All numbers called!")
        print("All numbers have been called.")  # Debugging line

# Create a button to call the next number
button = tk.Button(root, text="Call Number", command=call_number, font=("Helvetica", 16))
button.pack(pady=20)

# Run the Tkinter main loop
root.mainloop()
(Nov-06-2024, 02:56 PM)menator01 Wrote: Add a font setting in this line in the call_number function
self.last_number.config(text=number)
Add this
self.last_number.config(text=number, font= ("Courier", 128))
deanhystad write Nov-06-2024, 09:02 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#7
Please use the bbtags when posting code.

In the code you just provided it will be here.
label.config(text=number)
Change to
label.config(text=number, font=(None, 150))

The None can be a ttf or leave as None to use system default and the 150 will be whatever the size you want.


From your example

import tkinter as tk
from random import shuffle

# Create numbers - North American bing uses 75 numbers
bingo_numbers = (
["B" + str(i) for i in range(1, 16)] +
["I" + str(i) for i in range(16, 31)] +
["N" + str(i) for i in range(31, 46)] +
["G" + str(i) for i in range(46, 61)] +
["O" + str(i) for i in range(61, 76)]
)

# Make a copy to work with. Can keep original list
bn_copy = bingo_numbers[:]

# Shuffle list
shuffle(bn_copy)

# Function for getting bingo number
def call_number():
    # Set msg variable and font
    msg = ''
    font=(None, 80, 'bold')
    if bn_copy:
        number = bn_copy.pop(0)

        # Msg text and font size while the list is not empty
        msg = number
        font = ('comic sans ms', 80, 'bold')
    else:

        # Else list is empty set text and shrink size to fit window and label
        msg = 'All numbers have been called.'
        font = ('times', 18, 'italic')

    # Apply msg to label
    label.config(text=msg, font=font)

root = tk.Tk()
root.geometry('400x300')

label = tk.Label(root)
label.pack(fill='both', expand=True, pady=20)

button = tk.Button(root, text='Call Number', command=call_number)
button.pack(pady=20)

root.mainloop()
Playpatterns likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#8
It is easier to drop the starting and ending message and set the width of the called number label to a fixed width.
import random
import tkinter as tk

# Generate a list of all Bingo numbers
bingo_numbers = (
    [f"B" + str(i) for i in range(1, 16)]
    + ["I" + str(i) for i in range(16, 31)]
    + ["N" + str(i) for i in range(31, 46)]
    + ["G" + str(i) for i in range(46, 61)]
    + ["O" + str(i) for i in range(61, 76)]
)

# Shuffle the Bingo numbers randomly
random.shuffle(bingo_numbers)

# Create the main window using Tkinter
root = tk.Tk()
root.title("Bingo Caller")

# Create a label to display the Bingo number
label = tk.Label(root, text="", width=4, font=("Helvetica", 600))
label.pack(pady=20)

# Function to call the next Bingo number
def call_number():
    print("Button clicked!")  # Debugging line to ensure the function is called
    if bingo_numbers:  # Check if there are numbers left to call
        number = bingo_numbers.pop(0)
        label.config(text=number)
        print(f"Called number: {number}")  # Debugging line to check if a number is being popped
    else:  # If all numbers have been called
        label.config(text="END")
        print("All numbers have been called.")  # Debugging line


# Create a button to call the next number
button = tk.Button(root, text="Call Number", command=call_number, font=("Helvetica", 16))
button.pack(pady=20)
call_number()

# Run the Tkinter main loop
root.mainloop()
Instead of the start message telling you to press the call button, the program automatically makes the first call. There is no reason for the ending message telling you that no balls remain. It is impossible to reach this point without everyone having a bingo.

The important changes are removing this line so the window sizes to fit the contents.
root.geometry("400x300")  # Set the window size
And set a width for the called number display so the window doesn't resize each time a new number is called (very distracting).
label = tk.Label(root, text="", width=4, font=("Helvetica", 600))
And of course set a huge font.
Reply
#9
OMG it worked I LOVE it.

I'm so grateful for the information you shared.

The residents are going to be so happy, because they can see.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  coding a loot generator matt1984 1 1,259 Aug-16-2023, 05:08 AM
Last Post: Pedroski55
  General Coding Help biswajitmaity 2 2,362 Aug-25-2021, 03:04 PM
Last Post: jefsummers
  General coding Ellimann 2 3,029 Aug-25-2020, 05:43 AM
Last Post: buran
  General coding help prathmesh 1 2,399 Apr-01-2020, 01:23 PM
Last Post: buran
  general coding error karai 1 3,078 Mar-21-2018, 06:36 AM
Last Post: Gribouillis
  receive from a generator, send to a generator Skaperen 9 7,174 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020