在Python中循环问题的Tkinter按钮

时间:2018-04-26 17:56:22

标签: python python-3.x tkinter

我正在尝试构建一个简单的GUI,其中有一个句子列表,并且有一个for循环使用tkinter文本显示这些句子,我希望循环迭代并显示列表中的下一个句子单击按钮,我怎么能实现这一点,谢谢。我试过wait_variable但是它没有用。

var = IntVar()
for entry in input_texts:
    scroll = Scrollbar(canvas)
    display = Text(canvas, height=2, width=110)
    display.insert(INSERT, entry)
    display.grid(row=1, sticky='w')

    scroll.grid(row=1, column=4)
    display.config(yscrollcommand=scroll.set)
    scroll.config(command=display.yview)

    confirm = Button(canvas, text=" NEXT ", command=pause)
    confirm.grid(row=4, sticky='w')
    confirm.wait_variable(var)
    var.set(0)

canvas.resizable(width=False, height=False)
canvas.mainloop()

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。这是一种相当简单的方法。

import tkinter as tk

class Sentence:

    def __init__(self, master):
        self.text = tk.Text(master)
        self.scrolly = tk.Scrollbar(master, command=self.text.yview)
        self.scrolly.grid(row=0, column=1, sticky='nsw')
        self.text.grid(row=0, column=0, sticky='news')
        self.text['yscrollcommand'] = self.scrolly.set
        # Set the command attribute of the button to call a method that
        # inserts the next line into the text widget.
        self.button = tk.Button(master, text='Next', command=self.insertLine)
        self.button.grid(row=1, pady=10, column=0, sticky='n')
        self.data = ['Here is an example', 'This should be second', '3rd', 'and so on...']
        self.data.reverse()


    def insertLine(self):
        if len(self.data):
            # Pull the first line from the list and display it
            line = self.data.pop()
            self.text.insert(tk.END, line + '\n')
            self.text.see(tk.END)
        else:
            print("No more data")


if __name__ == '__main__':
    root = tk.Tk()
    sentence = Sentence(root)
    root.mainloop()