如何在Tkinter中将文本随机放置在标签中

时间:2019-12-22 08:49:21

标签: python python-3.x tkinter label tkinter-layout

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

    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()

2 个答案:

答案 0 :(得分:0)

最简单的方法是:

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

答案 1 :(得分:0)

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

这是经过必要修改的代码版本。我用名为 Label label小部件替换了您简单命名为Text的{​​{1}}。主要更改是num_display函数。

change_text()

下面是它运行并在随机位置显示数字之一的屏幕截图:

screenshot