tkinter GUI上的随机按钮

2024-09-19 23:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和tkinter构建一个选择题游戏,我需要能够在GUI上移动按钮,以便包含正确答案的按钮的位置发生变化。到目前为止,我已经编写了这段代码,但似乎相同的rely值经常多次从y_list中提取,导致按钮相互隐藏。如何确保每个rely值只取一次

y_list=[0.2,0.4,0.6,0.8]

def randy():
    xan = random.choice(y_list)
    return xan

y_list.remove(xan)


wordLabel = Label(newWindow, text=all_words_list[randWord])
wordLabel.place(relx=0.49, rely=0.1)
choice1=Button(newWindow, text=all_definitions_list[randDefinition], height=5, width=20)
choice1.place(relx=0.5,rely=randy(), anchor=N)
choice2=Button(newWindow, text="gangsta", height=5, width=20)
choice2.place(relx=0.5, rely=randy(), anchor=N)
choice3=Button(newWindow, text="gangsta", height=5, width=20)
choice3.place(relx=0.5, rely=randy(), anchor=N)
choice4=Button(newWindow, text="gangsta", height=5, width=20)
choice4.place(relx=0.5, rely=randy(), anchor=N)

Tags: textplacebuttonwidth按钮listanchorheight
1条回答
网友
1楼 · 发布于 2024-09-19 23:37:48

只需同时避免使用randy函数,并在random.shuffle()之后直接使用y_list

from random import shuffle

y_list = [0.2, 0.4, 0.6, 0.8]

shuffle(y_list)

wordLabel = Label(newWindow, text=all_words_list[randWord])
wordLabel.place(relx=0.49, rely=0.1)

choice1=Button(newWindow, text=all_definitions_list[randDefinition],
    height=5, width=20)
choice1.place(relx=0.5, rely=y_list[0], anchor=N)

choice2=Button(newWindow, text="gangsta", height=5, width=20)
choice2.place(relx=0.5, rely=y_list[1], anchor=N)

choice3=Button(newWindow, text="gangsta", height=5, width=20)
choice3.place(relx=0.5, rely=y_list[2], anchor=N)

choice4=Button(newWindow, text="gangsta", height=5, width=20)
choice4.place(relx=0.5, rely=y_list[3], anchor=N)

相关问题 更多 >