【问题标题】:Python tkinter multiple commands for one buttonPython tkinter 一键执行多个命令
【发布时间】:2017-12-05 20:16:50
【问题描述】:

我正在尝试使用tkinter 制作一个程序,当按下按钮时显示不同的单词。所以我的问题如下:假设有一个按钮 next question 并且每当按下它时,当前屏幕上的问题就会变为下一个(当前是 Q1 --> button 被按下 --> Q2 被替换Q1),我只想有一个按钮,而不是每个问题都有不同的按钮。我应该用什么来做到这一点?我尝试使用lists,但没有成功。

提前谢谢你们!

【问题讨论】:

  • 请提供您尝试过的最小版本。

标签: python button tkinter command


【解决方案1】:

最简单的解决方案是将问题放在一个列表中,并使用一个全局变量来跟踪当前问题的索引。 “下一个问题”按钮需要简单地增加索引,然后显示下一个问题。

使用类比使用全局变量要好,但为了使示例简短,我不会使用类。

例子:

import Tkinter as tk

current_question = 0
questions = [
    "Shall we play a game?",
    "What's in the box?",
    "What is the airspeed velocity of an unladen swallow?",
    "Who is Keyser Soze?",
]

def next_question():
    show_question(current_question+1)

def show_question(index):
    global current_question
    if index >= len(questions):
        # no more questions; restart at zero
        current_question = 0
    else:
        current_question = index

    # update the label with the new question.
    question.configure(text=questions[current_question])

root = tk.Tk()
button = tk.Button(root, text="Next question", command=next_question)
question = tk.Label(root, text="", width=50)

button.pack(side="bottom")
question.pack(side="top", fill="both", expand=True)

show_question(0)

root.mainloop()

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多