python - Python 中的 for 循环问题中的 Tkinter 按钮

标签 python python-3.x tkinter

我正在尝试构建一个简单的 GUI,其中有一个句子列表,并且有一个带有 tkinter Text 的 for 循环,其中显示这些句子,我希望循环迭代并仅在以下情况下显示列表中的下一个句子单击按钮,我该如何实现这一点,谢谢。我尝试了 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()

最佳答案

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

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

关于python - Python 中的 for 循环问题中的 Tkinter 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049283/

相关文章:

python - 使用 pyo3 的 python 扩展不会提高速度

python - 将文本文件(.txt 文件)与 python 中的列表串联?

python - 如何避免 Tkinter 中未处理的异常?

python - Virtualenv 中的 TKinter

python - 在 Tkinter 中交换

python - 通过 python 创建一个 vlan 并将其添加到网络命名空间

python - 将表达式分配给变量并执行它

Python 3.x - 计算绘图&&计算坐标系中可能的正方形

python - 在线程 django-main-thread : 中使用 StatReloader 异常监视文件更改

python - 基于Python的cmd模块创建交互式shell的自动化测试