[英]Adding a Scrollbar to a tkinter frame
我有以下一段代碼,當您單擊按鈕時列出了一些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()
正如您得到的錯誤所示,您不應在同一父級中同時使用pack
和grid
。 您應該閱讀這篇文章 ,可以更深入地了解同時使用pack
和grid
,並且還可以提供另一種選擇:從概念上將您的界面划分為多個部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.