Skip to content Skip to sidebar Skip to footer

How To Display And Update A Score On Screen?

My question is about displaying and updating text, in order to display the score on screen. I would like to create a score like the real game that would appear on the screen. But

Solution 1:

Here is one approach to display the scores: It uses a tk.Label, that is updated at the same time the score increases.

The trigger that increases the score is currently a random call to on_change; you can modify this to be a test if a pipe x coordinates becomes lower than the bird x coordinates (the bird successfully crossed the obstacle)

You can, if you want relocate the score label on the canvas.

import random
import tkinter as tk


WIDTH, HEIGHT = 500, 500defcreate_pipes():
    pipes = []
    for x inrange(0, WIDTH, 40):
        y1 = random.randrange(50, HEIGHT - 50)
        y0 = y1 + 50
        pipes.append(canvas.create_line(x, 0, x, y1))
        pipes.append(canvas.create_line(x, y0, x, HEIGHT))
    return pipes


defmove_pipes():
    for pipe in pipes:
        canvas.move(pipe, -2, 0)
        x, y0, _, y1 = canvas.coords(pipe)
        if x < 0:
            canvas.coords(pipe, WIDTH+20, y0, WIDTH+20, y1)

    if random.randrange(0, 20) == 10:
        on_change()

    root.after(40, move_pipes)


defon_change():
    global score
    score += 1
    score_variable.set(f'score: {score}')


root = tk.Tk()
tk.Button(root, text='start', command=move_pipes).pack()
score = 0
score_variable = tk.StringVar(root, f'score: {score}')
score_lbl = tk.Label(root, textvariable=score_variable)
score_lbl.pack()

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="cyan")
canvas.pack()

pipes = create_pipes()

root.mainloop()

Post a Comment for "How To Display And Update A Score On Screen?"