目前,我有这个:
from tkinter import *
from tkinter.ttk import *
class MainGUI(Frame):
chapters = []
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
#refresh function contents here
self.chapters.append("hi")
#
self.initUI()
def initUI(self):
self.parent.title("Latest Chapters")
self.style = Style()
#self.style.theme_use("default")
scrollbar = Scrollbar(self)
scrollbar.pack(side=RIGHT, fill=BOTH)
listbox = Listbox(self, yscrollcommand=scrollbar.set)
for newChapter in self.chapters:
listbox.insert(END, newChapter)
listbox.pack(side=TOP, fill=BOTH)
scrollbar.config(command=listbox.yview)
frame = Frame(self, relief=RAISED, borderwidth=1)
frame.pack(fill=BOTH, expand=True)
self.pack(fill=BOTH, expand=True)
closeButton = Button(self, text="Close", command=self.master.destroy)
closeButton.pack(side=RIGHT, padx=5, pady=5)
refreshButton = Button(self, text="Refresh Now", command=self.refresh)
refreshButton.pack(side=RIGHT)
def refresh(self):
self.chapters.append("hi")
#print("Refresh")
#refresh func here
self.initUI()
def main():
root = Tk()
root.geometry("300x207+300+300")
app = MainGUI(root)
root.mainloop()
if __name__ == '__main__':
main()
单击我的刷新按钮,chapters
数组附加了一个附加项。 chapters
数组已初始化,并在Listbox
中显示为initUI()
。当我单击 refresh 按钮时,我希望对GUI窗口中显示的chapters
数组进行更改。我不确定该怎么做 - 到目前为止,我已经尝试再次调用self.initUI()
,但它只是制作了多个较小的帧。感谢所有帮助!
答案 0 :(得分:1)
您可以通过Listbox
实例的MainGUI
属性来实现,以便您可以在refresh()
方法中轻松引用它。完成后,向chapters
列表和 Listbox
实例添加新项目非常简单:
这就是我的意思:
from tkinter import *
from tkinter.ttk import *
class MainGUI(Frame):
chapters = []
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
#refresh function contents here
self.chapters.append("hi")
self.initUI()
def initUI(self):
self.parent.title("Latest Chapters")
self.style = Style()
#self.style.theme_use("default")
scrollbar = Scrollbar(self)
scrollbar.pack(side=RIGHT, fill=BOTH)
self.listbox = Listbox(self, yscrollcommand=scrollbar.set)
for newChapter in self.chapters:
self.listbox.insert(END, newChapter)
self.listbox.pack(side=TOP, fill=BOTH)
scrollbar.config(command=self.listbox.yview)
frame = Frame(self, relief=RAISED, borderwidth=1)
frame.pack(fill=BOTH, expand=True)
self.pack(fill=BOTH, expand=True)
closeButton = Button(self, text="Close", command=self.master.destroy)
closeButton.pack(side=RIGHT, padx=5, pady=5)
refreshButton = Button(self, text="Refresh Now", command=self.refresh)
refreshButton.pack(side=RIGHT)
def refresh(self):
self.chapters.append("hi2") # add string to list
self.listbox.insert(END, self.chapters[-1]) # update Listbox
def main():
root = Tk()
root.geometry("300x207+300+300")
app = MainGUI(root)
root.mainloop()
if __name__ == '__main__':
main()
这里是几次单击立即刷新按钮后的样子。