0

我正在尝试使用 tkinter 中的按钮和标签来显示以下列表中的值:

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

这个想法是每次按下按钮时,标签都会显示列表中的下一个单词。

我最初的想法是使用这样的循环:

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])),

要删除第一个单词并在列表中显示新的第一个单词,但这显然只会在循环完成后显示列表中剩下的最后一个单词。

我想知道最好的方法是完成这样的事情。

4

2 回答 2

1

列表中的元素可以通过它们的索引来访问。您可以简单地存储按钮指向的当前索引。每次单击按钮时,更新索引并显示新单词:

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)

此方法允许您的按钮旋转单词,无论列表中有什么单词或列表有多长。

于 2018-09-12T01:34:03.337 回答
0

按钮小部件有一个命令选项,您可以使用它来实现在小部件中旋转文本的想法,无论是直接在按钮上还是在单独的标签小部件上。

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()
于 2018-09-12T02:44:52.247 回答