滚动条进入python tkinter讨论

时间:2015-08-05 06:45:54

标签: python canvas tkinter scrollbar

from tkinter import *

window = Tk()

ia_answers= "test\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)

input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)

def onFrameConfigure(canvas):
'''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
canvas = Canvas(window, borderwidth=0, background="white")
ia_frame = LabelFrame(canvas, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
scroll = Scrollbar(window, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scroll.set)

scroll.pack(side=RIGHT, fill=Y)
canvas.pack(fill=BOTH, expand=True)
canvas.create_window((4,4), window=ia_frame, anchor="nw")
ia_frame.bind("<Configure>", lambda event, canvas=canvas:onFrameConfigure(canvas))




user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify =   RIGHT, bg="white") 
user_text.pack(fill=X) 

ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = NW, justify = LEFT, bg="white") 
ia_text.pack(fill=X) 

user_texts = []
ia_texts = []
user_says_list = []
ia_says_list = []
def Enter_pressed(event):
    """Took the current string in the Entry field."""
    input_get = input_field.get()
    input_user.set("")
    user_says1 = StringVar()
    user_says1.set(input_get + "\n")
    user_text1 = Label(ia_frame, textvariable=user_says1, anchor = NE, justify =   RIGHT, bg="white") 
    user_text1.pack(fill=X)
    user_texts.append(user_text1)
    user_says_list.append(user_says1)
    ia_says1 = StringVar()
    ia_says1.set(ia_answers)
    ia_text1 = Label(ia_frame, textvariable=ia_says1, anchor = NW, justify = LEFT, bg="white") 
    ia_text1.pack(fill=X)
    ia_texts.append(ia_text1)
    ia_says_list.append(ia_says1)

input_field.bind("<Return>", Enter_pressed)
window.mainloop()

嗨,我尝试使用tkinter构建一个GUI,但是我遇到了两个问题,LabelFrame / Canvas没有完全填满窗口,我无法让滚动条自动向下滚动。 你能帮助我吗,非常感谢你。 Ilan Rossler。

1 个答案:

答案 0 :(得分:1)

您需要手动控制内框的宽度,因为它是由画布管理的。您可以将绑定中的宽度更改为画布的<Configure>事件(即:当画布更改大小时,您必须更改框架的大小)。

您需要能够在画布上引用窗口对象,这意味着您需要保存ID,或者为其添加标记。

以下是给它标记的示例:

canvas.create_window((4,4), window=ia_frame, anchor="nw", tags=("innerFrame",))

以下是画布更改大小时如何更改宽度:

def onCanvasConfigure(event):
    canvas = event.widget
    canvas.itemconfigure("innerFrame", width=canvas.winfo_width() - 8)

canvas.bind("<Configure>", onCanvasConfigure)

要向下滚动,请像滚动条一样调用yview命令。您需要在窗口有机会刷新后发生这种情况。

例如,将其添加为Enter_pressed中的最后一行:

def Enter_pressed(event):
    ...
    canvas.after_idle(canvas.yview_moveto, 1.0)