0

I am trying to use a button and label in tkinter to display values from the following list:

words = ["Australians", "all", "let", "us", "rejoice", "for", "we", "are",
         "young", "and", "free"]

The idea is that each time the button is pressed the label will display the next word in the list.

My inital idea was to use a loop like this:

def word_displayer():
    global words
    for word in words:
        if words[0] == "Australians":
            display.config(text=(words[0])),
            words.remove("Australians")
        elif words[0] == "all":
            display.config(text=(words[0])),

To remove the first word and display the new first word in the list but this will just obviously only display the last word left in the list once the loop is completed.

I was wondering what the best way is to accomplish something like this.

2
  • wrap the "for word in words" section in a while statement... then you can re-loop from the top Commented Sep 12, 2018 at 1:31
  • Is the word "all" misplaced? Commented Sep 12, 2018 at 2:03

2 Answers 2

1

Elements inside lists are accessible by their index. You can simply store the current index that the button is pointing at. Each time the button is clicked, update the index and display the new word:

def word_displayer():
  words = ["Australians", "all", "let", "us", "rejoice", "for", "we", "are",
     "young", "and", "free"]
  index = 0;
  display.config(text=(words[index]))

  def on_click():
    index = index + 1

    # Check if the index is pointing past the end of the list
    if (index >= len(words)):
      # If it is, point back at the beginning of the list
      index = 0
    display.config(text=(words[index]))

  display.bind('<Button-1>', on_click)

This method allows your button to rotate the words no matter what words are in the list or how long your list is.

Sign up to request clarification or add additional context in comments.

Comments

0

The button widget has a command option that you could use to implement the idea of rotating text in a widget, wether on the button directly or a separate label widget.

import tkinter as tk
anthem = ['with', 'golden', 'soil', 'and', 'wealth', 'for', 'toil']
length_of_song = 7
position = 0
ROOT = tk.Tk()
def sing_loop():
    global position, length_of_song
    sing['text'] = anthem[position]
    position = (position + 1) % length_of_song

sing = tk.Button(text='Press to sing',
                 command=sing_loop)
sing.pack(fill='both')
ROOT.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.