0

So basically im making blackjack for a high school project, Im trying to make the it and stand button now and i have all the functions, they worked in the non gui version and now they dont work with the gui. Heres my code any help will be appreciated:

# BlackJack

# Import required modules
import tkinter as tk
import tkinter.messagebox
import random

# Customize main window
root = tk.Tk()
root.title = ('Redemption BlackJack')
root.geometry('900x600') # This moves it to the middle of the screen becuase there is no title bar to move it with
root.resizable(False,False)
root.configure(bg='green')

# Create the frames and pack them
tframe = tk.LabelFrame (root, borderwidth = 0, bg='grey19')
tframe.pack(fill=tk.X,  expand = False, side = 'top', pady=15)
bframe = tk.LabelFrame (root, borderwidth = 0, bg='grey19')
bframe.pack(fill=tk.X,  expand = False, side='bottom', pady=15)


# Deck value and variables
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10,
        2, 3, 4, 5, 6, 7, 8, 9, 10,
        2, 3, 4, 5, 6, 7, 8, 9, 10,
        2, 3, 4, 5, 6, 7, 8, 9, 10,
        'J', 'Q', 'K', 'A', 'J', 'Q',
        'K', 'A', 'J', 'Q', 'K', 'A',
        'J', 'Q', 'K', 'A']

dealer_cards = []
player_cards = []
redemption_cards = []
player = 0
dealer = 0

# Functions needed to run the game
def dealcard(turn):
    card = random.choice(deck)
    turn.append(card)
    deck.remove(card)

# Total value and give face cards value
def totalvalue(turn):
    totalvalue = 0
    facecards = ['J', 'Q', 'K']
    for card in turn:
        if card in range(1, 11):
            totalvalue += card 
        elif card in facecards:
            totalvalue += 10 
        else:  # Chooses best value (11 / 1) for the Ace card
            if totalvalue > 11: 
                totalvalue += 1
            else:               
                totalvalue += 11
    return totalvalue

# Scoreboard
def stats():
    print('_____________________')
    print(f'Player\t\tDealer\n{player}\t\t{dealer}')
    print('---------------------')

# Redemption / new feature function
def redemption():
    total = 0
    if totalvalue(player_cards) > 21:
        input('Please claim your redemption by pressing any key')
        playerforcehit = (input('Please hit below \n1.Hit'))
        if playerforcehit == '1':
            dealcard(redemption_cards)
            if totalvalue(redemption_cards) >= 5:
                total = totalvalue(player_cards) - totalvalue(redemption_cards)
                print(f"The redemption card value is: {totalvalue(redemption_cards)}")
                print(f"Chance of redemption has been claimed, your new cards are {player_cards}, {redemption_cards} ")
                print(f"Your final total value is {total} ")
            else:
                total = totalvalue(player_cards) - totalvalue(redemption_cards)
                print(f"Seems like you hit and got a number {redemption_cards}, which is less than 5, so let's see what the dealer does.")

    return [total]

# Actual game code for the game to work
while True: # Loop
    # Variables that need to reset
    dealer_cards = []
    player_cards = []
    redemption_cards = []

    for dealing in range(2):
                dealcard(dealer_cards)
                dealcard(player_cards)
    # Create labels to display total card value and player cards
    playerscore = tk.Label(bframe, text = f'Players Total:\n{totalvalue(player_cards)}', font = 'times 20 bold', bg='grey19', fg='white')
    playerscore.pack(side=tk.LEFT)
    playercards = tk.Label(bframe, text = f'Your Cards:\n{player_cards}', font = 'times 20 bold', bg='grey19', fg='white')
    playercards.pack(side=tk.LEFT, padx = 75, expand=True)
    # Dealer labels
    dealerscore = tk.Label(tframe, text = f'Dealers Total:\n{totalvalue(dealer_cards)}', font = 'times 20 bold', bg='grey19', fg='white')
    dealerscore.pack(side=tk.LEFT)
    dealercards = tk.Label(tframe, text = f'Dealers Cards:\n{dealer_cards}', font = 'times 20 bold', bg='grey19', fg='white')
    dealercards.pack(side=tk.LEFT, padx = 75, expand=True)

    # Add buttons
    quit = tk.Button(root, command=root.destroy, text='Exit Game', height=4, width=20, bg='red3', highlightthickness=2, highlightbackground='black', font='times 13 bold')
    quit.pack(side=tk.RIGHT, padx=10)
    hit = tk.Button(root, command=dealcard(player_cards), text = 'Hit', height=4, width=20, bg='dodgerblue', highlightthickness=2, highlightbackground='black', font='times 13 bold')
    hit.pack(side=tk.RIGHT, padx=10)
    stand = tk.Button(bframe, text = 'Stand', height=4, width=20, bg='chocolate', highlightthickness=2, highlightbackground='black', font='times 13 bold')
    stand.pack(anchor='se', padx=10)

    root.mainloop() 

The code I mainly need help on is: command=dealcard(player_cards) this function is not running when i run the GUI.

hit = tk.Button(root, command=dealcard(player_cards), text = 'Hit', height=4, width=20, bg='dodgerblue', highlightthickness=2, highlightbackground='black', font='times 13 bold')
    hit.pack(side=tk.RIGHT, padx=10)
  • @jasonharper it does not update the text in the gui that displays the total value of cards and the player cards so i dont think it works. – MythInSpace Jan 18 '22 at 18:07
  • `dealcard()` does absolutely nothing to update the display, so that's the expected result. At least it's being called at the intended time, if you've applied one of the fixes from the linked question. – jasonharper Jan 18 '22 at 18:49
  • Is there a way to keep updating the labels, ive done a lot of research but i cant seem to find a way. – MythInSpace Jan 18 '22 at 18:56

2 Answers2

2

Changes I made:

  • Renamed playercards label to playercards_label because of the same name of the list and the label.
  • Changes [2,3,4,5....] to ["2D","3S","4C","5H"] to specify Diamond, Spade, Clubs and Hearts.
  • dealcard(turn) to dealcard(turn, labelElement=None) to change label text when new cards are dealt.

Code

# BlackJack

# Import required modules
import tkinter as tk
import tkinter.messagebox
import random

# Customize main window
root = tk.Tk()
root.title = "Redemption BlackJack"
root.geometry(
    "900x600"
)  # This moves it to the middle of the screen becuase there is no title bar to move it with
root.resizable(False, False)
root.configure(bg="green")

# Create the frames and pack them
tframe = tk.LabelFrame(root, borderwidth=0, bg="grey19")
tframe.pack(fill=tk.X, expand=False, side="top", pady=15)
bframe = tk.LabelFrame(root, borderwidth=0, bg="grey19")
bframe.pack(fill=tk.X, expand=False, side="bottom", pady=15)


# Deck value and variables
deck = [
    "2D","3D","4D","5D","6D","7D","8D","9D","10D",
    "2S","3S","4S","5S","6S","7S","8S","9S","10S",
    "2H","3H","4H","5H","6H","7H","8H","9H","10H",
    "2C","3C","4C","5C","6C","7C","8C","9C","10C",
    "J","Q","K","A","J","Q","K","A","J","Q","K","A","J","Q","K","A",]

dealer_cards = []
player_cards = []
redemption_cards = []
player = 0
dealer = 0

# Functions needed to run the game
def dealcard(turn, labelElement=None):
    card = random.choice(deck)
    turn.append(card)
    if labelElement:
        playercards_label.configure(text=f"Your Cards:\n{turn}")
    deck.remove(card)


# Total value and give face cards value
def totalvalue(turn):
    totalvalue = 0
    facecards = ["J", "Q", "K"]
    for card in turn:
        if card in range(1, 11):
            totalvalue += card
        elif card in facecards:
            totalvalue += 10
        else:  # Chooses best value (11 / 1) for the Ace card
            if totalvalue > 11:
                totalvalue += 1
            else:
                totalvalue += 11
    return totalvalue


# Scoreboard
def stats():
    print("_____________________")
    print(f"Player\t\tDealer\n{player}\t\t{dealer}")
    print("---------------------")


# Redemption / new feature function
def redemption():
    total = 0
    if totalvalue(player_cards) > 21:
        input("Please claim your redemption by pressing any key")
        playerforcehit = input("Please hit below \n1.Hit")
        if playerforcehit == "1":
            dealcard(redemption_cards)
            if totalvalue(redemption_cards) >= 5:
                total = totalvalue(player_cards) - totalvalue(redemption_cards)
                print(f"The redemption card value is: {totalvalue(redemption_cards)}")
                print(
                    f"Chance of redemption has been claimed, your new cards are {player_cards}, {redemption_cards} "
                )
                print(f"Your final total value is {total} ")
            else:
                total = totalvalue(player_cards) - totalvalue(redemption_cards)
                print(
                    f"Seems like you hit and got a number {redemption_cards}, which is less than 5, so let's see what the dealer does."
                )

    return [total]


# Actual game code for the game to work
while True:  # Loop
    # Variables that need to reset
    dealer_cards = []
    player_cards = []
    redemption_cards = []

    for dealing in range(2):
        dealcard(dealer_cards)
        dealcard(player_cards)
    # Create labels to display total card value and player cards
    print(dealer_cards, "\n", player_cards)
    playerscore = tk.Label(
        bframe,
        text=f"Players Total:\n{totalvalue(player_cards)}",
        font="times 20 bold",
        bg="grey19",
        fg="white",
    )
    playerscore.pack(side=tk.LEFT)
    playercards_label = tk.Label(
        bframe,
        text=f"Your Cards:\n{player_cards}",
        font="times 20 bold",
        bg="grey19",
        fg="white",
    )
    playercards_label.pack(side=tk.LEFT, padx=75, expand=True)
    # Dealer labels
    dealerscore = tk.Label(
        tframe,
        text=f"Dealers Total:\n{totalvalue(dealer_cards)}",
        font="times 20 bold",
        bg="grey19",
        fg="white",
    )
    dealerscore.pack(side=tk.LEFT)
    dealercards = tk.Label(
        tframe,
        text=f"Dealers Cards:\n{dealer_cards}",
        font="times 20 bold",
        bg="grey19",
        fg="white",
    )
    dealercards.pack(side=tk.LEFT, padx=75, expand=True)

    # Add buttons
    quit = tk.Button(
        root,
        command=root.destroy,
        text="Exit Game",
        height=4,
        width=20,
        bg="red3",
        highlightthickness=2,
        highlightbackground="black",
        font="times 13 bold",
    )
    quit.pack(side=tk.RIGHT, padx=10)
    hit = tk.Button(
        root,
        command=lambda: dealcard(player_cards, playercards_label),
        text="Hit",
        height=4,
        width=20,
        bg="dodgerblue",
        highlightthickness=2,
        highlightbackground="black",
        font="times 13 bold",
    )
    hit.pack(side=tk.RIGHT, padx=10)
    stand = tk.Button(
        bframe,
        text="Stand",
        height=4,
        width=20,
        bg="chocolate",
        highlightthickness=2,
        highlightbackground="black",
        font="times 13 bold",
    )
    stand.pack(anchor="se", padx=10)

    root.mainloop()

0

The Button command argument is firing off the dealcard function as soon as you are writing it.

hit = tk.Button(root, command=lambda : dealcard(player_cards), text = 'Hit', height=4, width=20, bg='dodgerblue', highlightthickness=2, highlightbackground='black', font='times 13 bold')
    hit.pack(side=tk.RIGHT, padx=10)

Use lambda function to make a anonymous function

  • it doesnt work, it just doesnt add a card to the players cards, i have text on the gui that displays the total value of the cards and the cards the user has is there a way to make them change of fix this issue? – MythInSpace Jan 18 '22 at 18:06
  • @MythInSpace Your cards are dealing properly but it isn't showing up because you are inside the mainloop in the while loop. Try adding print(turn) in the dealcard function, you will get the point. – Vivek K. Singh Jan 18 '22 at 18:56
  • Is there a way to keep updating the labels? – MythInSpace Jan 18 '22 at 18:57
  • @MythInSpace Yes, you can use label.configure(text="Updated text") – Vivek K. Singh Jan 18 '22 at 19:04
  • If its not any trouble can you show me how to use it, i just tried to use it and it doesnt update the total score when the hit button is pressed? – MythInSpace Jan 18 '22 at 19:08