Filippo
Filippo

Reputation: 97

Make scrollbar change length dynamically on Canvas tkinter

I've created a program in Python where i request some HTML through an urllib2 call and I print it on a Canvas item.

HTML source code is quite long so I tried to add a scrollbar to my canvas, but this one doesn't appear when the text is printed

Is there a way to make Scrollbar change dimension dinamically detecting the text lenght? Thank you in advance

This is my source code:

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()

Upvotes: 2

Views: 962

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385860

Once you add the text to the canvas, you need to update the scrollregion attribute so that the canvas knows how much of its virtual space should be scrollable.

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

Upvotes: 1

Related Questions