Tkinter:将新的widget打包到其他widget下面

2024-04-19 22:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试打包文本和滚动条小部件下面的按钮。在

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

我希望按钮在下面,而不是在其他小部件之间。在

我试过以下方法:

^{pr2}$

底部的按钮怎么包装?在

另一个问题是滚动条不起作用,当我试图滚动时什么也没有发生。 (是的,我尝试过用大量的行填充文本小部件,这超出了它的查看范围。)

另外,为什么滚动条在文本小部件之外查看/打包/“很远”?在


Tags: textfrom文本importselfmain部件def
2条回答

我认为您应该考虑用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
)

请尝试改用栅格几何图形管理器。

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

相关问题 更多 >