在Canvas tkinter上动态更改滚动条的长度

时间:2018-03-05 18:09:26

标签: python canvas tkinter tkinter-canvas

我在Python中创建了一个程序,我通过urllib2调用请求一些HTML,然后将它打印在Canvas项目上。

HTML源代码很长,所以我尝试在我的画布上添加滚动条,但是在打印文本时不会出现这个滚动条

有没有办法让滚动条改变尺寸,以检测文本长度?提前谢谢

这是我的源代码:

from tkinter import *
import urllib.request

def getURL():
    canvas.delete("all")

    with urllib.request.urlopen(entry.get()) as response:
        received_html = response.read()
    print(received_html)
    canvas.create_text(10,0,text=received_html, anchor=NW, width=700)

#Widget and item initialization
browser_window = Tk()
browser_window.geometry('900x700') # Size 900, 700
frame = Frame(browser_window) #frame
frame.pack(side=TOP, fill=BOTH, expand=5)
label = Label(frame, text= 'Inserisci URL:')
entry = Entry(frame)
canvas = Canvas(frame) #canvas
scrollbar = Scrollbar(frame, orient=VERTICAL, command=canvas.yview) 
#Scrollbar on my canvas


entry.insert(END, "http://jesolo.it")
#canvas configure
canvas.configure(yscrollcommand=scrollbar.set, background='#ffffff', 
scrollregion=canvas.bbox("all"))

button = Button(frame, text='Vai', command=getURL )



label.pack(side=TOP)
entry.pack(side=TOP)
button.pack(side=TOP)

scrollbar.pack(side=RIGHT, fill=Y) #Scrollbar pack
canvas.pack(side=LEFT, fill=BOTH, expand=5) #Canvas config
scrollbar.config(command=canvas.yview)

browser_window.mainloop()

1 个答案:

答案 0 :(得分:1)

将文本添加到画布后,需要更新scrollregion属性,以便画布知道应该可以滚动多少虚拟空间。

def getURL():
    ...
    canvas.create_text(10,0,text=received_html, anchor=NW, width=700)
    canvas.configure(scrollregion=canvas.bbox("all"))