【问题标题】:Learning Python. Having trouble with the tkinter widget.Grid manager and adding a scrollbar to a listbox widget学习 Python。 tkinter widget.Grid 管理器出现问题并将滚动条添加到列表框小部件
【发布时间】:2020-02-17 03:21:42
【问题描述】:

我从另一个问题中获得了大部分附加代码。我正在使用 Python 3.8。包管理器似乎很容易将滚动条小部件添加到列表框小部件。但是,我正在使用网格管理器。我无法让垂直滚动条正常工作。

当您运行此代码时,会出现一个垂直滚动条,但它并没有正确地物理连接到列表框小部件。顺便说一句:我让水平滚动条正常工作。

from tkinter import *

master = Tk()

listbox = Listbox(master)

scrollbar = Scrollbar(master, orient=VERTICAL)
scrollbar.grid(row=2, rowspan=50, column=40, sticky=N + S)

for i in range(50):
    listbox.insert(END, str(i))
listbox.grid(sticky="news")

scrollbar.config(command=listbox.yview)

mainloop()

【问题讨论】:

  • 使用pack()ListboxScrollbar 放入Frame,然后使用grid() 将此Frame 放入窗口
  • 你不必为Scrollbar 使用rowspan=50 - 即使你在Listbox 中放入50 行文本,Listbox 也只使用一行。
  • 使用listbox.grid(row=2, ...)
  • 你忘了tk.Listbox(..., yscrollcommand=scrollbar.set)
  • 我不知道您为什么要在我的答案中添加图片。我将其添加到您的问题中。

标签: python tkinter listbox grid pack


【解决方案1】:

您应该对这两个元素使用row=column= - 放在同一行和不同的列中。

你忘了tk.Listbox(..., yscrollcommand=scrollbar.set)

Scrollbar 不必使用rowspan=50 - 即使您插入 50 行文本,Listbox 也只使用一行。

import tkinter as tk # `import *` is not preferred (see PEP8)

master = tk.Tk()

scrollbar = tk.Scrollbar(master, orient='vertical')
scrollbar.grid(row=2, column=1, sticky='ns')

listbox = tk.Listbox(master, yscrollcommand=scrollbar.set)
for i in range(50):
    listbox.insert('end', str(i))
listbox.grid(row=2, column=0, sticky="news")

scrollbar.config(command=listbox.yview)

master.mainloop()

PEP 8 -- Style Guide for Python Code

【讨论】:

    【解决方案2】:

    如果您认为pack() 更简单,那么您可以将pack ListboxScrollbar 放在Frame 中,然后在框架上使用grid()

    import tkinter as tk
    
    master = tk.Tk()
    
    frame = tk.Frame(master)
    frame.grid(row=0, column=0) # set row and column to the desired position
    
    listbox = tk.Listbox(frame)
    listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
    
    scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=listbox.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    listbox.config(yscrollcommand=scrollbar.set)
    for i in range(50):
        listbox.insert(tk.END, str(i))
    
    master.mainloop()
    

    【讨论】:

    • 您的示例混合了包和网格管理器的工作原理并提供了适当的滚动条。但是,我读到不应在同一代码中同时使用两个管理器。
    • 您不能在 same 容器中混用 packgrid。在我的示例中,framelistboxscrollbar 的容器。而masterframe 的容器。
    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2018-05-02
    • 2019-12-26
    相关资源
    最近更新 更多