python 我可以在两个笔记本页面中复制列表框吗?



我正在使用python 3.4和tkinter。我有一个两页的笔记本。我有一个列表框,需要在两个页面上。

我想知道我是否可以设置一次列表框并在两个页面上使用它,或者我是否需要在每个页面上设置一个单独的列表框并在一个页面中的列表框更改时管理两者?

不能同时将列表框打包/网格/放置在两个不同的框架中。

但是,您可以在每次笔记本选项卡更改时重新打包/网格/放置列表框。为此,我使用了每次笔记本选项卡更改时触发的<<NotebookTabChanged>>事件:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()
frame1 = tk.Frame(notebook, bg='red', width=400, height=400)
frame1.pack_propagate(False)
frame2 = tk.Frame(notebook, bg='blue', width=400, height=400)
frame2.pack_propagate(False)
notebook.add(frame1, text='frame 1')
notebook.add(frame2, text='frame 2')
var = tk.StringVar(root, 'a b c d e f g')
listbox = tk.Listbox(notebook, listvariable=var)
def display_listbox(event):
tab = notebook.tabs()[notebook.index('current')]
listbox.pack(in_=tab)
notebook.bind('<<NotebookTabChanged>>', display_listbox)
root.mainloop()

关于display_listbox的解释:

  • notebook.tabs()返回(frame1, frame2)(即制表符的元组(
  • notebook.index('current')返回当前可见选项卡的索引
  • in_选项可用于指定我们要在其中打包列表框的小部件(它也适用于gridplace(

在两个列表框之间共享相同的listvariable足以使它们保持同步。

import tkinter as tk
from tkinter import ttk
rootWin = tk.Tk()
rootWin.title('Talk Like A Pirate')
listvar = tk.StringVar()
#create a notebook
pirateBook = ttk.Notebook(rootWin)
#create a tab
tab1 = tk.Frame(pirateBook)
#create a listbox in the tab
listbx1 = tk.Listbox(tab1,
listvariable=listvar,
height=21,
width=56,
selectmode='single'
)
listbx1.pack()
#create another tab
tab2 = tk.Frame(pirateBook)
#create a listbox in the second tab
listbx2 = tk.Listbox(tab2,
listvariable=listvar,
height=21,
width=56,
selectmode='single'
)
listbx2.pack()
#add the tabs to the notebook
pirateBook.add(tab1, text="Tab 1")
pirateBook.add(tab2, text="Tab 2")
#pack the notebook
pirateBook.pack()
#you can access the listbox through the listvariable, but that takes
#   a list as the argument so you'll need to build a list first:
ls=list()   #or you could just ls = []
#build a list for the list box
ls.append("Arr, matey!")
ls.append("Dead men tell no tales!")
ls.append("Heave ho, me hearties!")
ls.append("I'll cleave ye t'yer brisket a'fore sendin' ye to Davey Jones Locker!")
#then just set the list variable with the list
listvar.set(ls)
#or you can manipulate the data using Listbox()'s data manipulation
#   methods, such as .insert()
listbx1.insert(1, "Shiver me timbers!")
listbx2.insert(3, "Yo ho ho!")
listbx1.insert(5, "Ye scurvy dog!")
listbx2.insert('end', "Ye'll be walking the plank, Sharkbait!")
#you'll see this if you run this program from the command line
print(listbx1.get(5))
rootWin.mainloop()

例如,如果您将选项卡放在自己的类中,则这样做会有所不同,例如,使公共变量全局化,但同样的想法仍然适用:共享一个共同的listvariable

最新更新