我正在学习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()
答案 0 :(得分:1)
问题在于,您将msgfield
和inputbox
打包到self
而不是frame
,而self
是Tk实例有点不同于一个框架。尝试打包到你的框架中,我想你会得到你想要的行为(注意我在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()