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

时间:2014-05-23 23:04:48

标签: python python-2.7 tkinter widget

我试图将按钮打包在Text and 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 :(得分:2)

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

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

答案 1 :(得分:0)

我认为你应该考虑用ScrolledText字段替换文本字段。 它使用起来容易得多,不需要手动滚动条放置。 (请勿使用pack放置它。使用grid

import tkinter as tk
import tkinter.scrolledtext as tkst

self.chattext = tkst.ScrolledText(
    master = self,
    wrap   = tk.WORD,
    width  = 20,
    height = 10
)
相关问题