Python中循环问题的内部Tkinter按钮

2024-04-26 03:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个简单的GUI,其中有一个句子列表,并且有一个带有tkinter文本的for循环,在其中显示这些句子,我希望循环只在单击按钮时迭代并显示列表中的下一个句子,如何实现这一点,谢谢。我试过了,但没用。你知道吗

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

Tags: config列表forvardisplaywidthconfirmgrid
1条回答
网友
1楼 · 发布于 2024-04-26 03:04:17

有很多方法可以做到这一点。下面是一个相当简单的方法。你知道吗

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

相关问题 更多 >