带网格布局的Tkinter升降法

2024-05-26 21:52:35 发布

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

毫无疑问,这是一个新问题。我将Tkinter中的网格布局管理器与Python2.7一起使用。我想要一个按钮隐藏一个点击列表框。这是我目前的代码:

from Tkinter import *
root = Tk()
frame = Frame(root)
pyList = ["Eric", "Terry", "Graham", "Terry", "John", "Carol?", "Michael"]
arbList = ['ham', 'spam', 'eggs', 'potatos', 'tots', 'home fries']
pythons = Listbox(frame, width=10, height=5, selectmode=EXTENDED, exportselection=0)
food = Listbox(frame, width=10, height=5, selectmode=EXTENDED, exportselection=0)
def hider():
    if pythons.selection_includes(4):
        food.lower()
    elif pythons.selection_includes(0):
        food.lift()
b2 = Button(frame, text="Hide!", command=hider)
b2.grid(row=2, column=1)
food.grid(row=0, column=1)
pythons.grid(row=1, column=1, pady=10)
frame.grid()

for python in pyList:
        pythons.insert('end', python)

for thing in arbList:
        food.insert('end', thing)


root.mainloop()

不幸的是,胡闹这个似乎会抛出一个错误,说我不能把我的列表框提升/降低到框架的上方或下方。我已经让它和pack()管理器一起工作了,但不是grid()。

我错过了什么?


Tags: 管理器foodtkintercolumnrootwidthframegrid
2条回答

很抱歉,但这两个版本的代码对我都没有任何帮助。但是,以下修改确实有效。诀窍是让列表框的父级是root,而不是frame,让liftlowerframe相对。我想知道这是不是因为Tkinter的不同版本?

from Tkinter import *
root = Tk()
frame = Frame(root)
pyList = ["Eric", "Terry", "Graham", "Terry", "John", "Carol?", "Michael"]
arbList = ['ham', 'spam', 'eggs', 'potatos', 'tots', 'home fries']
pythons = Listbox(root, width=10, height=5, selectmode=EXTENDED, exportselection=0)
food = Listbox(root, width=10, height=5, selectmode=EXTENDED, exportselection=0)
def hider():
    if pythons.selection_includes(4):
        food.lower(frame)
    elif pythons.selection_includes(0):
        food.lift(frame)
b2 = Button(frame, text="Hide!", command=hider)
b2.grid(row=2, column=1)

food.grid(row=0, column=1, in_=frame)
pythons.grid(row=1, column=1, pady=10, in_=frame)
frame.grid()

for python in pyList:
        pythons.insert('end', python)

for thing in arbList:
        food.insert('end', thing)


root.mainloop()

不能将小部件放在其父级之下。根据official tk docs

If the aboveThis argument is omitted then the command raises window so that it is above all of its siblings in the stacking order (it will not be obscured by any siblings and will obscure any siblings that overlap it). If aboveThis is specified then it must be the path name of a window that is either a sibling of window or the descendant of a sibling of window. In this case the raise command will insert window into the stacking order just above aboveThis (or the ancestor of aboveThis that is a sibling of window); this could end up either raising or lowering window.

(注:。tkraise命令是lift()在最低级别实际调用的命令)

要获得所需的效果,请使帧和列表框同级,然后使用in_参数将列表框打包到帧中:

food.grid(row=0, column=1, in_=frame)
pythons.grid(row=1, column=1, pady=10, in_=frame)

相关问题 更多 >

    热门问题