Ballo Adam
Ballo Adam

Reputation: 105

Python tkinter multiple commands for one button

I am trying to make a program with tkinter that shows different words when a button is pressed. So my question is the following: say there is a button next question and whenever it is pressed the question that is currently on screen changes to the next one( current one is Q1 -- > button is pressed -- > Q2 replaced Q1), and I only want to have one singe button, not different ones for each question. What should I use to accomplish this? I tried using lists but it didn't work out.

Thank you guys in advance!

Upvotes: 0

Views: 976

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

The simplest solution is to put the questions in a list, and use a global variable to track the index of the current question. The "next question" button needs to simply increment the index and then show the next question.

Using classes would be better than global variables, but to keep the example short I won't use classes.

Example:

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

Upvotes: 1

Related Questions