Search code examples
pythontkintertkinter-canvasttkbootstrap

Tkinter Canvas wont change its color and scrollbar wont connect to Canvas


I have a class with my Main Window (App) inherited from ttkbootstrap.Window and a Canvas class inherited from ttkbootstrap.Canvas. Im creating an Object of the Canvas class in my MainWindow class (App) and when I add a Scrollbar in my App and connect it with the canvas, it wont scroll. Idk what Im doing wrong here.

Another problem is that when I type

self.bg = "red" 

in the Canvas class, my Canvas wont change its color.

(I "follow" the https://youtu.be/mop6g-c5HEY?t=28611 tutorial. But I want to use classes. Not what he does. The way he does it, works for me too)

I already tried to use

self.configure(bg= "red) 

but it wont work either

Using Tkinter instead of ttkbootstrap wont change anything, tried that too.

import ttkbootstrap as ttk
from random import randint, choice


class App(ttk.Window):
    def __init__(self, start_size):
        super().__init__()
        self.geometry(f"{start_size[0]}x{start_size[1]}")
        self.title("Tkinter Scrolling")
        
        self.canvas = Canvas(self)
        self.create_scrollbar()
        
        self.mainloop()
    
    def create_scrollbar(self):
        self.scrollbar = ttk.Scrollbar(self, orient= "vertical", command= self.canvas.yview)
        self.scrollbar.place(relx= 1, rely= 0, relheight= 1, anchor= "ne")
        self.canvas.configure(yscrollcommand= self.scrollbar.set) # WONT SCROLL

class Canvas(ttk.Canvas):
    def __init__(self, parent):
        super().__init__(parent)
        self.bg = "red"                            # WONT CHANGE COLOR
        self.scrollregion = (0,0, 2000, 5000)
        self.pack(expand= True, fill= "both")
        
        self.create_symbols()
    
    def create_symbols(self):
        self.create_line(0,0, 2000, 5000, fill= "green", width= 10)
        
        for i in range(100):
            left = randint(0,2000)
            top = randint(0, 5000)
            right = left + randint(10, 500)
            bottom = top + randint(10, 500)
            color = choice(("red", "green", "yellow", "orange"))
            self.create_rectangle(left, top, right, bottom,fill= color)

App((600,400))

Solution

  • NOTHING in Tkinter happens merely by assigning an attribute - self.bg = "red" has not chance of affecting the display, self.configure(bg= "red") should have worked (but might not have any visible effect, if your random rectangles entirely filled the Canvas). Scrolling isn't working because you haven't set a scrollregion - again, attribute vs. .config() method. – jasonharper