1

我正在学习 Tkinter 并尝试创建一个正常的聊天风格窗口。但是,在调整窗口大小时,尽管设置了 expand=1,但仍有一些意想不到的结果,例如项目之间出现灰色框。

另外,如何设置它以便在将窗口大小调整为小于原始大小时共享空间?

这是我的代码:

from Tkinter import *

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()

    def initUI(self):
        frame = Frame(self, relief=RAISED, borderwidth=1)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.msgfield = Text(self, wrap=WORD, yscrollcommand=scrollbar.set)

        self.msgfield.pack(side=TOP, fill=BOTH, expand=1)
        self.msgfield.config(state=DISABLED)

        self.inputbox = Text(self, height=2, width=30)
        self.inputbox.pack(fill=BOTH, side=BOTTOM, expand=0)
        self.inputbox.bind('<Return>', self.retrieve_input)

        frame.pack(fill=BOTH, expand=1, side=BOTTOM)
        self.pack(fill=BOTH, expand=1, side=TOP)

    def retrieve_input(self, event):
        msg = self.inputbox.get(1.0, END)[:-1]

        self.msgfield.config(state=NORMAL)
        self.msgfield.insert(END, msg)
        self.msgfield.see(END)             # Scroll if necessary
        self.msgfield.config(state=DISABLED)
        self.inputbox.delete(0.0, END)

def main():
    root = Tk()
    root.geometry("300x400+300+300")
    app = Example(root)
    root.mainloop()  

if __name__ == '__main__':
    main()  
4

1 回答 1

1

问题是您将您的msgfield和打包inputboxself而不是frame, 并且self是 Tk 实例,它的作用与 Frame 有点不同。尝试打包到你的框架中,我想你会得到你想要的行为(注意我在 Text 小部件中添加了一个黑色边框,以便我可以看到它):

from Tkinter import *


class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent

        frame = Frame(self, relief=RAISED, borderwidth=1)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.msgfield = Text(frame, wrap=WORD, yscrollcommand=scrollbar.set)

        self.msgfield.pack(side=TOP, fill=BOTH, expand=1)
        self.msgfield.config(state=DISABLED)

        self.inputbox = Text(frame, height=2, width=30, borderwidth=2)
        self.inputbox.config(highlightbackground="Black")
        self.inputbox.pack(fill=BOTH, side=BOTTOM, expand=0)
        self.inputbox.bind('<Return>', self.retrieve_input)

        frame.pack(fill=BOTH, expand=1, side=BOTTOM)
        self.pack(fill=BOTH, expand=1)

    def retrieve_input(self, event):
        msg = self.inputbox.get(1.0, END)[:-1]

        self.msgfield.config(state=NORMAL)
        self.msgfield.insert(END, msg)
        self.msgfield.see(END)             # Scroll if necessary
        self.msgfield.config(state=DISABLED)
        self.inputbox.delete(0.0, END)


def main():
    root = Tk()
    root.geometry("300x400+300+300")
    app = Example(root)
    app.mainloop()

if __name__ == '__main__':
    main()
于 2013-11-12T23:04:33.020 回答