Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Cannot use geometry manager pack inside

So I'm making an rss reader using the tkinter library, and in one of my methods I create a text widget. It displays fine until I try to add scrollbars to it.

Here is my code before the scrollbars:

   def create_text(self, root):
        self.textbox = Text(root, height = 10, width = 79, wrap = 'word')
        self.textbox.grid(column = 0, row = 0)

Here is my code after:

def create_text(self, root):
        self.textbox = Text(root, height = 10, width = 79, wrap = 'word')
        vertscroll = ttk.Scrollbar(root)
        vertscroll.config(command=self.textbox.yview)
        vertscroll.pack(side="right", fill="y", expand=False)
        self.textbox.config(yscrllcommand=vertscroll.set)
        self.textbox.pack(side="left", fill="both", expand=True)
        self.textbox.grid(column = 0, row = 0)

This gives me the error

_tkinter.TclError: cannot use geometry manager pack inside .56155888 which already has slaves managed by grid on the line vertscroll.pack(side="right", fill="y", expand=False)

Any ideas how to fix this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Per the docs, don't mix pack and grid in the same master window:

Warning: Never mix grid and pack in the same master window. Tkinter will happily spend the rest of your lifetime trying to negotiate a solution that both managers are happy with. Instead of waiting, kill the application, and take another look at your code. A common mistake is to use the wrong parent for some of the widgets.

Thus, if you call grid on the textbox, do not call pack on the scrollbar.


import Tkinter as tk
import ttk

class App(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.create_text()

    def create_text(self):
        self.textbox = tk.Text(self.master, height = 10, width = 79, wrap = 'word')
        vertscroll = ttk.Scrollbar(self.master)
        vertscroll.config(command=self.textbox.yview)
        self.textbox.config(yscrollcommand=vertscroll.set)
        self.textbox.grid(column=0, row=0)
        vertscroll.grid(column=1, row=0, sticky='NS')

root = tk.Tk()
app = App(root)
root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...