简体   繁体   中英

Tkinter: Pack new widgets below other widgets

I'm trying to pack the button below the Text and Scrollbar widget.

#!/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()

This is what it looks like 它看起来像什么

I want the button to be below and not in between the other widgets.

I have tried the following:

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

How may i pack the button at the bottom?

Another issue is that the scrollbar does not work, when i try to scroll nothing happens. (Yes, i have tried to fill the Text widget with alot of lines, more than it can view.)

Also, why is the scrollbar viewed/packed outside/"far" away from the Text widget?

Try using the grid geometry manager instead.

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

I think you should consider replacing the text field with a ScrolledText field. It's a lot easier to use and doesn't require manual scrollbar placement. (Don't use pack to place it though. Use grid )

import tkinter as tk
import tkinter.scrolledtext as tkst

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM