0

这是我正在使用的代码:

import sys
from tkinter import *
from random import choice
def motiv():
    motiv1 = mLabel = Label(text='Waste not, want not', fg="red").pack()
    motiv2 = mLabel = Label(text='Sticks and stones', fg="red").pack()
    motiv3 = mLabel = Label(text='Keep holding on', fg="red").pack()
    motiv4 = mLabel = Label(text='Hold On, Pain Ends', fg="red").pack()

    ranMotiv = [motiv1, motiv2, motiv3, motiv4]
    print (choice(ranMotiv))

mGui = Tk()

mGui.geometry('450x450+500+150')
mGui.title('RMM')

mLabel = Label(text='Welcome to the Random Motivation Machine', fg="red").pack()

mButton = Button(text = "Click for Some Motivation", command = motiv)
mButton.pack()

mGui.mainloop() 

没有错误,但它会同时打印出所有这些文本,而我希望它只随机打印出其中的一个。

我的目标是让某人按下按钮并在 GUI 窗口中弹出一个随机短语。

所以有人按下按钮,四个文本短语中只有一个出现在窗口上:

1.不浪费,不想要。

2.棍棒和石头

3.坚持下去。

4.坚持,痛苦结束。

我相信我的麻烦就来自这个领域:

ranMotiv = [motiv1, motiv2, motiv3, motiv4]
print (choice(ranMotiv))

有没有人有任何想法?这只是我的一个非常小的宠物项目。我只使用 Python 不到几个月,所以我不是很精明。顺便说一句,我正在运行 Python 3.2.5。谢谢大家。

4

2 回答 2

1

I originally posted this as a comment, but it turned out to be the answer, so I'm reposting it here:

The problem is that Label(text='Waste not, want not', fg="red").pack() packs the label right away. Doing this with all labels causes them to be packed. It doesn't matter if you call random.choice later because the labels have already been packed into your GUI.

If you want to create a random label from a pool of labels, What you want to do is this:

def motiv():
    myLabels = ['Waste not, want not', 'Sticks and stones', 'Keep holding on', 'Hold On, Pain Ends']
    chosenLabel = random.choice(myLabels)
    randMotiv = Label(text=chosenLabel, fg="red").pack()
于 2013-07-27T22:15:58.023 回答
0

这个怎么样:

from tkinter import *
from random import choice

# Place the messages outside of the function so that they are not
# re-created each time the button is pressed
messages = ['Waste not, want not', 'Sticks and stones',
'Keep holding on', 'Hold On, Pain Ends']

def motiv():

    # Just update the text of the Label instead of create a whole new one
    message["text"] = choice(messages)

mGui = Tk()

mGui.geometry('450x450+500+150')
mGui.title('RMM')

mLabel = Label(text='Welcome to the Random Motivation Machine', fg="red").pack()

mButton = Button(text = "Click for Some Motivation", command = motiv)
mButton.pack()

# Make a Label to hold the messages that will be updated with each click of the button
message = Label(fg="red")
message.pack()

mGui.mainloop()

这种方法不仅仅是在 GUI 底部添加一条新消息,而是更简洁,并且只是更新消息的文本。它还修复了从 GUI 运行消息的问题(您可以通过单击按钮 30 次来看到这一点)。

于 2013-07-28T14:07:03.947 回答