Tkinter:在其他控件下打包新控件

0 投票
2 回答
3246 浏览
提问于 2025-04-18 07:27

我正在尝试把下面的按钮放在文本和滚动条控件的下面。

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

这看起来是这样的:

看起来是这样的

我希望按钮在下面,而不是夹在其他控件中间。

我尝试了以下方法:

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

我该如何把按钮放在最底下呢?

还有一个问题是,滚动条不工作,我尝试滚动时什么也没有发生。 (是的,我已经尝试在文本控件中填入很多行,超过它能显示的行数。)

另外,为什么滚动条看起来/放置得离文本控件这么远呢?

2 个回答

1

我觉得你可以考虑把文本框换成一个叫做 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
)
2

试试用网格布局管理器吧。

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

撰写回答