如何在 Tkinter 中随机定位标签中的文本

How to position a text in a label randomly in Tkinter

我是编码的初学者,而不是 Python 的初学者。老师给了我们一个游戏项目,我们要开发一个记忆游戏,首先我们选择难度(要记住多少个数字)然后这些数字将以 1 秒的间隔一个一个出现,然后用户将提交答案。如果用户答对了所有数字,则进入下一级别(将难度增加一个),否则退出。但这些数字必须随机 positions.but 出现在我的标签上,他们出现在特定位置有没有办法让数字出现在随机位置?

    from tkinter import *
from random import*
from tkinter import simpledialog
from tkinter import messagebox


def check():
    global difficulty
    global entered_correctly
    global a

    content = int(e.get())
    if content == sequence[a]:
        label_result['text'] = "correct"
        entered_correctly = entered_correctly + 1
        if entered_correctly == difficulty:
            messagebox.showinfo("Congratulations", "YOU WIN")
            entered_correctly = 0
            difficulty = difficulty + 1
            create_sequence()
            show_sequence()

    else:
        messagebox.showinfo("You entered the wrong number", " YOU LOSE!")
        root.quit()
    a = a + 1

def get_me():
    global difficulty
    difficulty = simpledialog.askinteger("Choose the difficulty", "Enter a positive integer")
    if difficulty != 0:
        button.forget()
        pack_widgets()
        create_sequence()
def start():
    button.pack()
def pack_widgets():
    e.pack()
    btn_check.pack(fill=X, pady=10)
    label_result.pack()
    label_result.after(1000, show_sequence)
def create_sequence():
    for k in range(0, difficulty):
        sequence.append(randint(0, 20))
def show_sequence():
    label.pack()
    k = 1
    seconds = 1
    global counter
    while 1:
        if counter == difficulty:
            break
        label.after(1000*k, change_text)
        counter = counter + 1
        k = k+1
    counter = 0
def change_text():
    global i
    label["text"] = sequence[i]
    i = i+1

entered_correctly = 0
a = 0
i = 0
difficulty = 0
counter = 0
root = Tk()
root.title("Memory Game")
root.geometry("600x480")
button = Button(root, text="Start", command=get_me)
sequence = []
e = Entry(root)
btn_check = Button(root, fg="green", bg="white", command=check,  text="Check", bd=5)
label = Label(root, width=80, height=40, text='')
label_result = Label(root, width=20, height=5, text='', bg="brown", fg="blue")
start()
root.mainloop()

最简单的方法是:

import random
Label(label_attributes).place(x=random.randint(0, window_width), y=random.randint(0, window_height))

我建议您使用 Text 小部件,而不是使用 Label 并尝试在其中的随机位置放置文本,因为它支持在随机行和列位置插入文本。

这是经过必要修改后的代码版本。我将您简单命名为 labelLabel 替换为名为 num_displayText 小部件。主要更改是 change_text() 函数。

from tkinter import *
from random import*
from tkinter import simpledialog
from tkinter import messagebox

DSP_WIDTH, DSP_HEIGHT = 40, 15  # Dimensions of number display.


def check():
    global difficulty
    global entered_correctly
    global a

    content = int(e.get())
    if content == sequence[a]:
        label_result['text'] = "correct"
        entered_correctly = entered_correctly + 1
        if entered_correctly == difficulty:
            messagebox.showinfo("Congratulations", "YOU WIN")
            entered_correctly = 0
            difficulty = difficulty + 1
            create_sequence()
            show_sequence()

    else:
        messagebox.showinfo("You entered the wrong number", " YOU LOSE!")
        root.quit()
    a = a + 1

def get_me():
    global difficulty
    difficulty = simpledialog.askinteger("Choose the difficulty", "Enter a positive integer")
    if difficulty != 0:
        button.forget()
        pack_widgets()
        create_sequence()

def start():
    button.pack()

def pack_widgets():
    e.pack()
    btn_check.pack(fill=X, pady=10)
    label_result.pack()
    label_result.after(1000, show_sequence)

def create_sequence():
    for k in range(0, difficulty):
        sequence.append(randint(0, 20))

def show_sequence():
    num_display.pack()
    k = 1
    seconds = 1
    global counter
    while 1:
        if counter == difficulty:
            break
        num_display.after(1000*k, change_text)
        counter = counter + 1
        k = k+1
    counter = 0
    num_display.after(1000*k, clear)  # Erase last number displayed.

def clear():
    """ Clear by deleting current contents and filling with blank lines. """
    num_display.delete('1.0', END)
    for k in range(DSP_HEIGHT):
        num_display.insert(f'{k}.0', ' '*(DSP_WIDTH-2) + '\n')

def change_text():
    global i

    # Display next number at random position on number display.
    line = randint(0, DSP_HEIGHT-2) + 1
    column = randint(0, DSP_WIDTH-2)
    posn = f'{line}.{column}'
    clear()
    num_display.insert(posn, sequence[i])
    i = i+1

entered_correctly = 0
a = 0
i = 0
difficulty = 0
counter = 0
root = Tk()
root.title("Memory Game")
root.geometry("600x480")
button = Button(root, text="Start", command=get_me)
sequence = []
e = Entry(root)
btn_check = Button(root, fg="green", bg="white", command=check,  text="Check", bd=5)
#label = Label(root, width=80, height=40, text='')
num_display = Text(root, width=DSP_WIDTH, height=DSP_HEIGHT)
label_result = Label(root, width=20, height=5, text='', bg="brown", fg="blue")
start()
root.mainloop()

这是它的屏幕截图 运行 并在随机位置显示其中一个数字: