2017-12-05 4 views
0

tkinterのボタンを押したときに異なる単語を表示するプログラムを作成しようとしています。だから私の質問は、次のとおりです:ボタンがあると言うとnext questionと、それが押されるたびに現在の画面が次のものに変わります(現在はQ1 - >buttonが押されて - > Q2がQ1に置き換えられます)。私はそれぞれの質問に対して異なるものではなく、ただ一つのボタンを持っていたい。これを達成するために私は何を使用すべきですか?私はlistsを使ってみましたが、うまくいきませんでした。Python tkinter 1つのボタンの複数のコマンド

ありがとうございます!

+0

あなたが試したものの最低限のバージョンを提供してください。 – Nae

答えて

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

ありがとうございます! –

関連する問題