如何在Python tkinter中重叠小部件/框架?

9

我想知道这是否可能。我的目标是在一个较大的文本框的上方右下角放置一个小白色框,这个白色框将被用作“信息框”,当人们滚动文本框内的文本时显示。

当我说“文本框”时,我指的是tkinter中的Text。


尝试使用以下方法:https://dev59.com/XnM_5IYBdhLWcg3wMgAF - Totem
@Totem:我认为那是一个不同的问题。 - Bryan Oakley
1个回答

9
使用“place”几何管理器可以将一个小部件放在其他小部件的顶部。您可以指定相对于其他小部件的x/y坐标,以及指定绝对或相对宽度和高度。 effbot网站上有关于place几何管理器的良好写作:http://effbot.org/tkinterbook/place.htm。下面是一个简单的例子:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="word")
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=self.text_yview)
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

        # create an info window in the bottom right corner and
        # inset a couple of pixels
        self.info = tk.Label(self.text, width=20, borderwidth=1, relief="solid")
        self.info.place(relx=1.0, rely=1.0, x=-2, y=-2,anchor="se")

    def text_yview(self, *args):
        ''' 
        This gets called whenever the yview changes.  For this example
        we'll update the label to show the line number of the first
        visible row. 
        '''
        # first, update the scrollbar to reflect the state of the widget
        self.vsb.set(*args)

        # get index of first visible line, and put that in the label
        index = self.text.index("@0,0")
        self.info.configure(text=index)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

谢谢,它完美地运行了。然而,我还有另一个问题。我正在尝试找出如何在Text TKinter Python项目中查找文本光标的当前位置。文本光标指的是闪烁在您所写的文本旁边的“|”。 - user3033423
@user3033423:self.text.index("insert")将以行.字符的形式返回插入光标的索引。 - Bryan Oakley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接