我正在尝试构建一个简单的 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/