如何使用 Tkinter 绑定标签小部件,以便每当用户在他/她的键盘上键入特定键时,它就会突出显示? Python 打字游戏

问题描述 投票:0回答:1

我正在使用 Python 构建打字速度游戏,并且在绑定一些小部件时遇到问题。

我从 Youtube 上获得了以下视频的灵感:https://www.youtube.com/watch?v=ktv8nNhTDu4&ab_channel=CodingLifestyle4u

我想为用户提供视觉帮助,这样,每当他/她输入某些内容时,按下的键就会在虚拟键盘(使用标签创建)上以蓝色突出显示。

我对此很陌生,这是我的投资组合的第一个项目的一部分。

抱歉,如果代码不完整,如果我尝试全部输入,Stackoverflow 会说我的代码看起来像垃圾邮件。

我感谢您提供的任何帮助。

找到下面的代码。

Pd。我还没有完成使按钮工作的功能。我被标签的绑定困住了,我真的需要理解为什么它不起作用。

import tkinter as tk
from tkinter import ttk
import ttkthemes
import random

# Window
root = ttkthemes.ThemedTk()
root.get_themes()
root.set_theme("radiance")
root.title("Typing Speed App")
root.geometry("1200x800+500+100")
root.resizable(width=0, height=0)

# Main Frame
main_frame = tk.Frame(master=root)
main_frame.grid(row=0, column=0)

title_frame = tk.Frame(master=main_frame)
title_frame.grid(row=0, column=0)

title_label = tk.Label(master=title_frame, text="Typing Speed Application", font=("algerian", 28, "bold"), bg="orange", fg="white", width=50)
title_label.grid(row=0, column=0)

# Texts to make the app work.
texts = open(file="texts.txt", mode="r").read().split("\n")

# Frame to display the texts to be typed.
text_to_be_typed_frame = tk.Frame(master=main_frame)
text_to_be_typed_frame.grid(row=1, column=0)

text_to_be_typed_label = tk.Label(master=text_to_be_typed_frame, text=random.choice(texts), font=("arial", 14, "bold"), fg="black", width=100, 
                                        height=3, wraplength=1000, justify="left")
text_to_be_typed_label.grid(row=0, column=0)

# Frame to receive the user's input.
answer_frame = tk.Frame(master=main_frame)
answer_frame.grid(row=2, column=0)

answer_text = tk.Text(master=answer_frame, font=("arial", 14), bg="white", fg="black", height=5, bd=4, relief="groove", wrap="word", state="disabled")
answer_text.grid(row=0, column=0)

# Frame to display the stats of the app.
stats_frame = tk.Frame(master=main_frame)
stats_frame.grid(row=3, column=0)

stats_label = tk.Label(master=stats_frame, text="Statistics", font=("arial", 18, "bold"))
stats_label.grid(row=0, column=0, columnspan=6, pady=5)

elapsed_time_label = tk.Label(master=stats_frame, text="Elapsed Time:", font=("tahoma", 12, "bold"), fg="red")
elapsed_time_label.grid(row=1, column=0, padx=3)

elapsed_time_counter_label = tk.Label(master=stats_frame, text="0.00", font=("tahoma", 12, "bold"), fg="black")
elapsed_time_counter_label.grid(row=1, column=1, padx=3, sticky="e")

words_per_minute_label = tk.Label(master=stats_frame, text="WPM:", font=("tahoma", 12, "bold"), fg="red")
words_per_minute_label.grid(row=2, column=0, padx=3, sticky="e")

words_per_minute_counter_label = tk.Label(master=stats_frame, text="0", font=("tahoma", 12, "bold"), fg="black")
words_per_minute_counter_label.grid(row=2, column=1, padx=3)

accuracy_label = tk.Label(master=stats_frame, text="Accuracy:", font=("tahoma", 12, "bold"), fg="red")
accuracy_label.grid(row=1, column=2, padx=3, sticky="e")

accuracy_label_counter_label = tk.Label(master=stats_frame, text="0.00 %", font=("tahoma", 12, "bold"), fg="black")
accuracy_label_counter_label.grid(row=1, column=3, padx=3)

wrong_words_label = tk.Label(master=stats_frame, text="Wrong Words:", font=("tahoma", 12, "bold"), fg="red")
wrong_words_label.grid(row=1, column=4, padx=3, sticky="e")

wrong_words_counter_label = tk.Label(master=stats_frame, text="0", font=("tahoma", 12, "bold"), fg="black")
wrong_words_counter_label.grid(row=1, column=5, padx=3)

total_words_label = tk.Label(master=stats_frame, text="Total Words:", font=("tahoma", 12, "bold"), fg="red")
total_words_label.grid(row=2, column=4, padx=3, sticky="e")

total_words_counter_label = tk.Label(master=stats_frame, text="0", font=("tahoma", 12, "bold"), fg="black")
total_words_counter_label.grid(row=2, column=5, padx=3)

# Frame to display all the action buttons.
buttons_frame = tk.Frame(master=main_frame)
buttons_frame.grid(row=4, column=0)

start_button = ttk.Button(master=buttons_frame, text="Start")
start_button.grid(row=0, column=0, padx=20, pady=5)

assisted_button = ttk.Button(master=buttons_frame, text="Assisted")
assisted_button.grid(row=0, column=1, padx=20, pady=5)

reset_button = ttk.Button(master=buttons_frame, text="Reset", state="disabled")
reset_button.grid(row=0, column=2, padx=20, pady=5)

exit_button = ttk.Button(master=buttons_frame, text="Exit")
exit_button.grid(row=0, column=3, padx=20, pady=5)

# Frame to display the assistance keyboard.
keyboard_frame = tk.Frame(master=main_frame)
keyboard_frame.grid(row=5, column=0)

# Frame to display the first row of the keyboard
frame1strow = tk.Frame(master=keyboard_frame)
frame1strow.grid(row=0, column=0)

""" ALL THE CORRESPONDING KEYS ARE SET AS LABELS IN HERE """

# Frame to display the second row of the keyboard
frame2ndrow = tk.Frame(master=keyboard_frame)
frame2ndrow.grid(row=1, column=0)

""" ALL THE CORRESPONDING KEYS ARE SET AS LABELS IN HERE """

# Frame to display the third row of the keyboard
frame3rdrow = tk.Frame(master=keyboard_frame)
frame3rdrow.grid(row=2, column=0)

""" ALL THE CORRESPONDING KEYS ARE SET AS LABELS IN HERE """

# Frame to display the fourth row of the keyboard
frame4throw = tk.Frame(master=keyboard_frame)
frame4throw.grid(row=3, column=0)

""" ALL THE CORRESPONDING KEYS ARE SET AS LABELS IN HERE """

# Frame to display the fifth row of the keyboard
frame5throw = tk.Frame(master=keyboard_frame)
frame5throw.grid(row=4, column=0)

""" ALL THE CORRESPONDING KEYS ARE SET AS LABELS IN HERE """

binding_dictionary = {
    "~": label, "`": label, 
    "!": label_1, "1": label_1, 
    "@": label_2, "2": label_2,
    "#": label_3, "3": label_3,
    "$": label_4, "4": label_4,
    "%": label_5, "5": label_5,
    "^": label_6, "6": label_6,
    "&": label_7, "7": label_7,
    "*": label_8, "8": label_8,
    "(": label_9, "9": label_9,
    ")": label_0, "0": label_0,
    "_": label_01, "-": label_01,
    "+": label_02, "=": label_02,
    "tab": label_tab,
    "Q": label_q, "q": label_q,
    "W": label_w, "w": label_w,
    "E": label_e, "e": label_e,
    "R": label_r, "r": label_r,
    "T": label_t, "t": label_t,
    "Y": label_y, "y": label_y,
    "U": label_u, "u": label_u,
    "I": label_i, "i": label_i,
    "O": label_o, "o": label_o,
    "P": label_p, "p": label_p,
    "{": label_03, "[": label_03,
    "}": label_04, "]": label_04,
    "|": label_05,
    "caps\nlock": label_caps_lock,
    "A": label_a, "a": label_a,
    "S": label_s, "s": label_s,
    "D": label_d, "d": label_d,
    "F": label_f, "f": label_f,
    "G": label_g, "g": label_g,
    "H": label_h, "h": label_h,
    "J": label_j, "j": label_j,
    "K": label_k, "k": label_k,
    "L": label_l, "l": label_l,
    ":": label_06, ";": label_06,
    '"': label_07,
    "Return": label_08,
    "shift": label_shift,
    "Z": label_z, "z": label_z,
    "X": label_x, "x": label_x,
    "C": label_c, "c": label_c,
    "V": label_v, "v": label_v,
    "B": label_b, "b": label_b,
    "N": label_n, "n": label_n,
    "M": label_m, "m": label_m,
    "<": label_09, ",": label_09,
    ">": label_10, ".": label_10,
    "?": label_11, "/": label_11,
    "shift": label_12,
    "ctrl": label_ctrl,
    "alt": label_alt,
    "space": label_space,
    "alt": label_13,
    "fn": label_14,
}

def change_bg(widget):
    widget.config(bg="blue")
    widget.after(1000, lambda : widget.config(bg="black"))

for key in binding_dictionary:
    root.bind(key, lambda event, label=binding_dictionary[key]:change_bg(label))

root.mainloop()
python tkinter binding
1个回答
0
投票

您的问题表明用户输入的键应该突出显示。那为什么要打开并读取文本文件呢?

假设您想突出显示用户按下的键,我在这里给出了代码的特定部分。了解想法并根据您的要求修改其余代码。

您不需要为所有键创建

dict
。相反,您只需将所需的小部件与
'<key>'
和所需的函数绑定即可。

from tkinter import *

def highlight_text(event):

    # get the key pressed by the user
    key_pressed = event.keysym
    
    # configure the widget typed_txt with text being key_pressed and fg being blue
    typed_txt.config(text = key_pressed, fg = 'blue')

root = Tk()
root.geometry("1200x800+500+100")

lbl_txt = Label(root, text = 'Type Text', font="arial 14 bold", fg="black")
lbl_txt.pack()

# A text box where the user types the text
user_text = Text(root, width = 100, height = 10)
user_text.pack()

# Bind the widget user_text with '<key>' and the function highlight_text
user_text.bind('<Key>', highlight_text)

#create a label for highlighting the text without the text parameter
# Ensure that the font-size being very big
typed_txt = Label(root, font="arial 200 bold")
typed_txt.pack()

root.mainloop() 
© www.soinside.com 2019 - 2024. All rights reserved.