将滚动条添加到tkinter框架

时间:2018-10-22 12:39:09

标签: python tkinter

我有以下一段代码,单击按钮时列出了一些URL。我想将滚动条添加到列出网址的底部框架中。不幸的是,我目前的尝试导致“无法在已经由包管理从站的。!frame2内部使用几何管理器网格”。

我可以看到我正在混合网格和打包,但是到目前为止我还没有解决这个问题。有人可以帮我吗?

import random
import tkinter as tk
import webbrowser

class Pierre:
        """This class holds all the objects, data and functions for a single 
    line"""
    def __init__(self, master, url):
        self.url = url
        self.counter = 0
        _, i = master.grid_size() # get the current row number

        lbl = tk.Label(master, text=url, fg="blue", cursor="hand2")
        lbl.grid(row=i, column=1)
        lbl.bind("<Button-1>", self.callback)

        self.DisplayButton = tk.Button(master, text = self.counter)
        self.DisplayButton.grid(row=i, column=2)
        self.DisplayButton.config(height = 1, width = 1 )

        self.Plus1Button = tk.Button(master, text = "+1", command=self.plus1, bg="green")
        self.Plus1Button.grid(row=i, column=3)
        self.Plus1Button.config(height = 1, width = 1 )

        self.Neg1Button = tk.Button(master, text = "-1", command=self.neg1, bg="green")
        self.Neg1Button.grid(row=i, column=4)
        self.Neg1Button.config(height = 1, width = 1 )

    def plus1(self):
        self.counter += 1
        self.DisplayButton["text"]=str(self.counter)

    def neg1(self):
        self.counter -= 1
        self.DisplayButton["text"]=str(self.counter)

    def callback(self, event):
        webbrowser.open_new(self.url)

class TestClass(tk.Tk):
    def __init__(self, **kwargs):
        tk.Tk.__init__(self, **kwargs)
        self.title('Test')

        self.topframe = tk.Frame(self)
        self.topframe.pack( side = tk.TOP, pady=30)

        self.bottomframe = tk.Frame(self)
        self.bottomframe.pack( side = tk.BOTTOM )

        self.canvas=tk.Canvas(self.bottomframe)
        self.hbar=tk.Scrollbar(self.bottomframe,orient=tk.HORIZONTAL)
        self.hbar.pack(side=tk.BOTTOM,fill=tk.X)
        self.hbar.config(command=self.canvas.xview)
        self.vbar=tk.Scrollbar(self.bottomframe,orient=tk.VERTICAL)
        self.vbar.pack(side=tk.RIGHT,fill=tk.Y)
        self.vbar.config(command=self.canvas.yview)
        self.canvas.config(width=300,height=300)
        self.canvas.config(xscrollcommand=self.hbar.set, 
    yscrollcommand=self.vbar.set)
        self.canvas.pack(side=tk.LEFT,expand=True,fill=tk.BOTH)


        self.button = tk.Button(self.topframe, text='Click', command = 
    self.output_value)
        self.button.pack(side="left", fill="both", expand=True)

    ####define the function that the submit button will do
    def output_value(self):
        urls = ["http://www.google.com", "http://www.facebook.com"]
        for url in urls:
            Pierre(self.bottomframe, url)

if __name__ == "__main__":
    root = TestClass()
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

如您得到的错误所示,您不应在同一父级中同时使用packgrid。 您应该阅读this post,以便更深入地了解同时使用packgrid时的操作,还可以给您一种选择:概念上将您的界面分为多个部分。