文本小部件内联在可滚动框架中

时间:2017-06-19 11:34:49

标签: python tkinter

我想水平对齐文本小部件,并且能够向左和向右滚动放置这些小部件的框架。下面的代码几乎就是我想要的,除了我的滚动条无法正常工作。

我找到了一些例子,据说在Canvas中不使用包或网格。但是,如果我使用场所布局,我的小部件就会消失。

from tkinter import *


class MainView(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.canvas = Canvas(self)
        self.sensorsStatsFrame = Frame(self.canvas)
        myscrollbar = Scrollbar(self,orient=HORIZONTAL,command=self.canvas.xview)
        myscrollbar.pack(side=BOTTOM,fill=X)
        self.canvas.configure(xscrollcommand=myscrollbar.set)
        self.canvas.pack(side=TOP, fill=BOTH)

        test0 = Text(self.sensorsStatsFrame, bg="red", state=DISABLED, width=150)
        test1 = Text(self.sensorsStatsFrame, bg="green")
        test0.pack(side=LEFT)
        test1.pack(side=LEFT)

        self.canvas.create_window((0,0),window=self.sensorsStatsFrame,anchor='nw')
        self.canvas.config(scrollregion=self.canvas.bbox("all"))


if __name__ == "__main__":
    root = Tk()
    main = MainView(root)
    main.pack(fill="both", expand=1)
    root.wm_geometry("1100x500")
    root.wm_title("MongoDB Timed Sample Generator")
    root.mainloop()

1 个答案:

答案 0 :(得分:1)

我想水平对齐文本小部件,并能够左右滚动放置这些小部件的框架。

如果我没有误解你,你应该为你的代码添加一个事件功能。

from tkinter import *


class MainView(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.canvas = Canvas(self)
        self.sensorsStatsFrame = Frame(self.canvas)
        myscrollbar = Scrollbar(self,orient=HORIZONTAL,command=self.canvas.xview)
        myscrollbar.pack(side=BOTTOM,fill=X)
        self.canvas.configure(xscrollcommand=myscrollbar.set)
        self.canvas.pack(side=TOP, fill=BOTH)

        test0 = Text(self.sensorsStatsFrame, bg="red", state=DISABLED, width=150)
        test1 = Text(self.sensorsStatsFrame, bg="green")
        test0.pack(side=LEFT)
        test1.pack(side=LEFT)

        self.canvas.create_window((0,0),window=self.sensorsStatsFrame,anchor='nw')
# Call the function like the below.
        self.sensorsStatsFrame.bind("<Configure>", self.onFrameConfigure)
# Add below function to your codes.
    def onFrameConfigure(self, event):
        self.canvas.config(scrollregion=self.canvas.bbox("all"))


if __name__ == "__main__":
    root = Tk()
    main = MainView(root)
    main.pack(fill="both", expand=1)
    root.wm_geometry("1100x500")
    root.wm_title("MongoDB Timed Sample Generator")
    root.mainloop()