首页 文章

Tkinter:在其他小部件下面打包新的小部件

提问于
浏览
0

我正在尝试打包Text和Scrollbar小部件下面的按钮 .

#!/usr/bin/python

try:
  from Tkinter import *
except ImportError:
  from tkinter import *

class Chat(Frame):
  def __init__(self, master):
    Frame.__init__(self, master)
    self.pack(anchor=N, fill=BOTH)
    self.create_widgets()
    self.count = 0

  def create_widgets(self):
    self.scrolly = Scrollbar(self)
    self.scrolly.pack(side=RIGHT, fill=Y)
    self.chattext = Text(self, borderwidth=5, yscrollcommand=self.scrolly.set)
    self.chattext.pack(side=LEFT)
    self.scrolly.config(command=Text.yview(self.chattext))
    self.button1 = Button(self, text="Add text", command=self.add_text)
    self.button1.pack()

  def add_text(self):
    self.count += 1
    self.chattext.insert("end", "%i\n" % self.count)
    self.chattext.update_idletasks()


def main():
  root = Tk()
  root.title("Test Chat Client")
  root.geometry("600x500")
  #root.resizable(0,0)
  app = Chat(root)

  root.mainloop()

if __name__ == "__main__":
  main()

这就是它的样子
What it looks like

我希望按钮位于下方而不是其他小部件之间 .

我尝试过以下方法:

self.button1.pack(after=self.scrolly)
self.button1.pack(after=self.chattext)

我怎么可以在底部打包按钮?

另一个问题是滚动条不起作用,当我尝试滚动没有任何反应 . (是的,我试图用很多行来填充Text小部件,而不是它可以查看 . )

另外,为什么滚动条在文本窗口小部件的外部/“远”处被查看/打包?

2 回答

  • 0

    请尝试使用网格几何管理器 .

    http://www.tkdocs.com/tutorial/grid.html

  • 2

    我认为你应该考虑用ScrolledText字段替换文本字段 . 它's a lot easier to use and doesn'需要手动滚动条放置 . (不要使用 pack 来放置它 . 使用 grid

    import tkinter as tk
    import tkinter.scrolledtext as tkst
    
    self.chattext = tkst.ScrolledText(
        master = self,
        wrap   = tk.WORD,
        width  = 20,
        height = 10
    )
    

相关问题