您不应该使用循环来创建您的窗口。您设置函数的方式将一次创建所有窗口。
下面的代码将根据列表本身创建窗口,因此当您想要更改“下一步”按钮将转到的页数时,您需要做的就是更新列表。
请记住,这种方式可能不是处理列表的最佳方法。对于更清晰的 OOP 方法,您可能希望在 Class 中编写一些内容。下面仅用于展示如何使用该列表来决定接下来要创建的 Toplevel。
from tkinter import *
root = Tk()
mylist = [1,2,3,4,5]
current_toplevel = None
def go_cmd(x):
# global is used to make variables that are outside of the function
# in the global namespace accessible.
global current_toplevel, mylist
wx = root.winfo_x()
wy = root.winfo_y()
next_index = x + 1
# This will check if the next_index variable will be within the available
# index range and if next_index is outside the index range it will reset
# to index zero. This will prevent the "outside index" error.
if next_index not in list(range(len(mylist))):
next_index = 0
# if the variable current_toplevel is not set to none then destroy it
# so we can create the next window.
if current_toplevel != None:
current_toplevel.destroy()
current_toplevel = Toplevel()
# set the location of the new top level window based off of the
# root windows location. This can be changed to anything but
# I wanted to use this as the example.
current_toplevel.geometry("+{}+{}".format(wx, wy))
Label(current_toplevel, width = 10, text = mylist[x]).grid(row=0,column=0)
# because we need to prep the "Next" button for the next index
# we will need to use a lambda command for getting the next window
b = Button(current_toplevel, width = 10, text="Next",
command = lambda a = next_index: go_cmd(a)).grid(row=1,column=0)
b1 = Button(root,text = "Go", width = 10,
command = lambda: go_cmd(0)).grid(row=0,column=0)
root.mainloop()
这是没有所有说明性注释的代码。
从 tkinter 导入 *
root = Tk()
mylist = [1,2,3,4,5]
current_toplevel = None
def go_cmd(x):
global current_toplevel, mylist
wx = root.winfo_x()
wy = root.winfo_y()
next_index = x + 1
if next_index not in list(range(len(mylist))):
next_index = 0
if current_toplevel != None:
current_toplevel.destroy()
current_toplevel = Toplevel()
current_toplevel.geometry("+{}+{}".format(wx, wy))
Label(current_toplevel, width = 10, text = mylist[x]).grid(row=0,column=0)
b = Button(current_toplevel, width = 10, text="Next",
command = lambda a = next_index: go_cmd(a)).grid(row=1,column=0)
b1 = Button(root,text = "Go", width = 10,
command = lambda: go_cmd(0)).grid(row=0,column=0)
root.mainloop()