ethancoder
ethancoder

Reputation: 1

How to create a scrollable canvas that scrolls without a scroll bar in python?

I have been making an rpg with various scenes in it that I can go to. I am trying to have a window that is the same size on all of my scenes, so that on the larger ones the window will scroll over to the other part of the screen when my character goes toward the edge of the screen.

from tkinter import*
top = Tk()
top.title("Lemonkingdom Quest")

#For Directional Purposes
up = False
down = False
left = False
right = False

#when a var has a b in front of it, it refers
#to if they hero is present in that scene or location
#when false they are not there, when true they are
bcave1=False
bcastle=False
bmarket=False
bforest1 = False
bforest2 = False

class Chart:
        chart = Canvas(top,width=120,height=120,background="black",highlightthickness=0)
        chart.grid(row=0,column=0)
        cycle_period = 10
        cycle_period2 = 10



#This Class allows for creation of Actors, with pictures,
#Each Actor Has its own Canvas ID, assigned in the order they are created
class Person:
    def __init__(self,person,x,y,picture,items):
        self.person = person
        self.x = x
        self.y = y
        self.picture = picture
        self.items = items
        Chart.chart.create_image(x,y,image=picture,anchor=NW)
class Actor:
    def __init__(self,person,x,y,picture):
        self.person = person
        self.x = x
        self.y = y
        self.picture = picture
        Chart.chart.create_image(x,y,image=picture,anchor=NW)

Person("Hero",60,60,herodownstand,None) # ID = 1 when first created
#the globalized hero refers to the ID, after each scene
#all the Actors are deleted to allow for new actors to be inputted
#at that time the hero variable is changed to be the new ID of the
#hero that is created 
hero = Person("Hero",60,60,herodownstand,None)

# the xx and yy variables refer to the coordinates that the hero is at
# they help by being changed before they act to see if there is a wall in the
# way of them
xx = 60
yy = 60



class Item:
    def __init__(self,item,x,y,picture,owner):
        self.item = item
        self.x = x
        self.y = y
        self.picture = picture
        self.owner = owner
        Chart.chart.create_image(x,y,image=picture,anchor=NW)
    def grab(i,h):
        i.owner = h
    def discard(i,h):
         i.owner = None

Key=Item("Key",60,60,keypic,None)
#These Are Lists of Walls And other Objects that can be inputted

def market():
#240,120 is a space, 150,30 is a space
        s = 150
        t = 60
        Chart.chart.delete(ALL)
        Actor("Hero",s,t,herodownstand)
        global hero
        (hero,) = Chart.chart.find_closest(s,t,halo=None,start=None)
        global yy
        global xx
        xx = s
        yy = t
        global marketground
        global bforest2
        global bforest1
        global bmarket
        global bcastle
        global marketwall
        global bcave1
        bcave1=False
        bforest2 = False
        bforest1 = False
        bmarket = True
        bcastle = False
        #for (x,y) in marketground:
        #        Actor("",x,y,ground)
      #  Chart.chart.configure(width=270,height=210,background_image=tk.PhotoImage(ground.gif))
        Chart.chart.configure(width=270,height=210,background=None)
        Actor("door",150,0,marketwalldoortop)
        Actor("door",150,30,marketwalldoorbottom)
        print("just in the Market")
        for (x,y) in marketwall: 
                Actor("wall",x,y,marketwallpic)
                print("in the IF MARKET")

def castle():
        s = 150
        t = 150
        Chart.chart.delete(ALL)
        Actor("Hero",s,t,heroupstand)
        global hero
        sss= Chart.chart.find_closest(s,t,halo=None,start=None)
        (hero,)=sss
        global yy
        global xx
        yy = s
        xx = t
        global bforest2
        global bforest1
        global bcastle
        global bmarket
        global marketwall
        global bcave1
        bcave1=False
        print("at the castle MANN")
        bforest1=False
        bforest2=False
        bcastle = True
        bmarket = False
        Chart.chart.configure(width=270,height=180,background=None)
        for (x,y) in castlewall:
                Actor("wall",x,y,marketwallpic)
def forest1():
        s = 0
        t = 30
        Chart.chart.delete(ALL)
        Actor("Hero",s,t,herorightstand)
        global hero
        (hero,) = Chart.chart.find_closest(s,t,halo=None,start=None)
        global yy
        global xx
        xx = s
        yy = t
        global ground
        global bforest2
        global forest2wall
        global bforest1
        global bmarket
        global bcastle
        global marketwall
        global forest1wall
        global bcave1
        bcave1=False
        bforest2 = False
        bforest1 = True
        bmarket = False
        bcastle = False
        Chart.chart.configure(width=270,height=330,background=("black"))
        Actor("door",-30,30,gatepic)
        print("in the FOREST")
        for (x,y) in forest1wall: 
                Actor("wall",x,y,treepic)
                print("in the FOREST")
#        for (x,y) in treetop: 
 #               Actor("wall",x,y,treepic)
  #              print("in the FOREST")
def forest2():
        s = 210
        t = 0
        Chart.chart.delete(ALL)
        Actor("Hero",s,t,herodownstand)
        global hero
        (hero,) = Chart.chart.find_closest(s,t,halo=None,start=None)
        global yy
        global xx
        xx = s
        yy = t
        global cave1doorR
        global cave
        global bforest2
        global bforest1
        global bmarket
        global bcastle
        global marketwall
        global forest1wall
        global forest2wall
        global bcave1
        bcave1=False
        bforest2 = True
        bforest1 = False
        bmarket = False
        bcastle = False
        Chart.chart.configure(width=270,height=330,background=None)
        Actor("door",210,-30,gatepic)
        print("in the FOREST")
        for (x,y) in forest2wall: 
                Actor("wall",x,y,treepic)
                print("in the FOREST")
        for (x,y) in cave:
                Actor("wall",x,y,cavepic)
                print("by the cave")
        for (x,y) in cave1doorR:
                Actor("wall",x,y,cavedoorR)
def cave1():
        s = 180
        t = 30
        Chart.chart.delete(ALL)
        Actor("Hero",s,t,heroleftstand)
        global hero
        (hero,) = Chart.chart.find_closest(s,t,halo=None,start=None)
        global yy
        global xx
        xx = s
        yy = t
        global key1
        global cave1wall
        global cave1doorL
        global cave
        global bforest2
        global bforest1
        global bmarket
        global bcastle
        global marketwall
        global forest1wall
        global forest2wall
        global bcave1
        global Key
        bcave1 = True
        bforest2 = False
        bforest1 = False
        bmarket = False
        bcastle = False
        Chart.chart.configure(width=240,height=360,background=None)
        for (x,y) in cave1wall: 
                Actor("wall",x,y,cavepic)
        for (x,y) in key1:
            if Key.owner == None:
                Item("Key",x,y,keypic,None)
            else:
                None
        for (x,y) in cave1doorL:
                Actor("wall",x,y,cavedoorL)


#These Are the Moving Methods
class Move:
    def checkwallup(x):
        global up
        global down
        global left
        global right
        global xx
        global yy
        global marketwall
        global castlewall
        global bforest2
        global bmarket
        global bcastle
        global bforest1
        global forest1wall
        global forest2wall
        global cave
        global cave1doorR
        global cave1doorL
        global bcave1
        global cave1wall
        global key1
        global Key
        global hero
   #     global treetop
        yy = yy - 30
        pos = (xx,yy)
        if bmarket == True:
            if pos in marketwall:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)
            elif pos == (150,30):
                if Key.owner == hero:
                    Move.moveup(x)
                else:
                    Chart.chart.itemconfigure(x,image=heroupstand)

            elif pos == (150,0):
               if Key.owner == hero:
                    castle()
               else:
                    Chart.chart.itemconfigure(x,image=heroupstand)
            else:
                Move.moveup(x)
        elif bcastle == True:
            if pos in castlewall:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)
            else:
                Move.moveup(x)
        elif bforest1 == True:
            if pos in forest1wall:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)
            else:
                Move.moveup(x)
        elif bforest2 == True:
            if pos in forest2wall:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)
            elif pos in cave:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)
            elif pos == (210,-30):
                forest1()
            elif pos in cave1doorR:
                 yy = yy + 30
                 Chart.chart.itemconfigure(x,image=heroupstand)
            else:
                Move.moveup(x)
        elif bcave1==True:
            if pos in cave1wall:
                yy = yy + 30
                Chart.chart.itemconfigure(x,image=heroupstand)            
            elif pos in key1:
                if Key.owner == None:  
                    yy = yy + 30
                    Chart.chart.itemconfigure(x,image=heroupstand)
                else:
                    Move.moveup(x)
            elif pos in cave1doorL:
                 yy = yy + 30
                 Chart.chart.itemconfigure(x,image=heroupstand)
            else:
                Move.moveup(x)
    def checkwalldown(x):
        global up
        global down
        global left
        global right
        global xx
        global yy
        global marketwall
        global castlewall
        global bmarket
        global bcastle
        global bforest2
        global forest2wall
        global bforest1
        global forest1wall
        global cave
        global cave1doorL
        global cave1doorR
        global bcave1
        global cave1wall
        global key1
        global Key
        global hero
#       global treetop
        yy = yy + 30
        pos = (xx,yy)
        if bmarket == True:
            if pos in marketwall:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            else:
                Move.movedown(x)
        elif bcastle == True:
            if pos in castlewall:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos == (150,180):
                    market()
            else:
                Move.movedown(x)
        elif bforest1 == True:
            if pos in forest1wall:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos == (210,330):
                forest2()
#            if pos in treetop:
#                yy = yy - 30
#                Chart.chart.itemconfigure(x,image=herodownstand)
            else:
                Move.movedown(x)
        elif bforest2 == True:
            if pos in forest2wall:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos in cave:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos in cave1doorR:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            else:
                Move.movedown(x)
        elif bcave1 == True:
            if pos in cave1wall:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos in cave1doorL:
                yy = yy - 30
                Chart.chart.itemconfigure(x,image=herodownstand)
            elif pos in key1:
                if Key.owner == None:  
                    yy = yy - 30
                    Chart.chart.itemconfigure(x,image=herodownstand)
                else:
                    Move.movedown(x)
            else:
                Move.movedown(x)

    def checkwallleft(x):
        global up
        global down
        global left
        global right
        global xx
        global yy
        global marketwall
        global castlewall
        global bmarket
        global bcastle
        global bforest1
        global bforest2
        global forest2wall
        global forest1wall
        global cave
        global cave1doorR
        global cave1doorL
        global cave1wall
        global bcave1
        global key1
        global Key
        global hero
  #      global treetop
        xx = xx - 30
        pos = (xx,yy)
        if bmarket == True:
            if pos in marketwall:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            else:
                Move.moveleft(x)
        elif bcastle == True:
            if pos in castlewall:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            else:
                Move.moveleft(x)
        elif bforest1 == True:
            if pos in forest1wall:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            elif pos == (-30,30):
                    market()
   #         if pos in treetop:
   #             xx = xx + 30
   #             Chart.chart.itemconfigure(x,image=heroleftstand)
            else:
                Move.moveleft(x)
        elif bforest2 == True:
            if pos in forest2wall:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            elif pos in cave:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            elif pos == (60,240):
                    cave1()

            else:
                Move.moveleft(x)
        elif bcave1 == True:
            if pos in cave1wall:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            elif pos in cave1doorL:
                xx = xx + 30
                Chart.chart.itemconfigure(x,image=heroleftstand)
            elif pos in key1:
                if Key.owner == None:  
                    xx = xx + 30
                    Chart.chart.itemconfigure(x,image=heroleftstand)
                else:
                    Move.moveleft(x)
            else:
                Move.moveleft(x)
    def checkwallright(x):
        global up
        global down
        global left
        global right
        global xx
        global yy
        global marketwall
        global castlewall
        global bmarket
        global bcastle
        global bforest1
        global bforest2
        global forest2wall
        global forest1wall
        global cave
        global cave1doorR
        global cave1doorL
        global cave1wall
        global bcave1
        global key1
        global Key
        global hero
    #    global treetop
        xx = xx + 30
        pos = (xx,yy)
        if bmarket == True:
            if pos in marketwall:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            elif pos == (270,120):
                    forest1()
            else:
                Move.moveright(x)
        elif bcastle == True:
            if pos in castlewall:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            else:
                Move.moveright(x)
        elif bforest1 == True:
            if pos in forest1wall:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
 #           if pos in treetop:
  #              xx = xx - 30
   #             Chart.chart.itemconfigure(x,image=herorightstand)
            else:
                Move.moveright(x)
        elif bforest2 == True:
            if pos in forest2wall:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            elif pos in cave:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            elif pos in cave1doorR:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            else:
                Move.moveright(x)
        elif bcave1 == True:
            if pos in cave1wall:
                xx = xx - 30
                Chart.chart.itemconfigure(x,image=herorightstand)
            elif pos in key1:
                if Key.owner == None:                
                    xx = xx - 30
                    Chart.chart.itemconfigure(x,image=herorightstand)
                else:
                    Move.moveright(x)
            elif pos == (210,30):
                forest2()
            else:
                Move.moveright(x)
    def moveup(x):
        global up
        global down
        global left
        global right 
        up = True
        down = False
        right = False
        left = False
        Chart.chart.itemconfigure(x,state=NORMAL)
        Chart.chart.itemconfigure(x,image=heroupstand)
        for i in range(1,11):
                Chart.chart.move(x,0,-1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroupwalk1)
        for i in range(1,11):
                Chart.chart.move(x,0,-1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroupwalk2)
        for i in range(1,11):
                Chart.chart.move(x,0,-1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroupstand)
    def movedown(x):
        global up
        global down
        global left
        global right
        up = False
        down = True
        left =  False
        right = False
        Chart.chart.itemconfigure(x,state=NORMAL)
        Chart.chart.itemconfigure(x,image=herodownstand)
        for i in range(1,11):
                Chart.chart.move(x,0,1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=herodownwalk1)
        for i in range(1,11):
                Chart.chart.move(x,0,1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=herodownwalk2)
        for i in range(1,11):
                Chart.chart.move(x,0,1)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=herodownstand)          
    def moveleft(x):
        global up
        global down
        global left
        global right
        up = False
        down = False
        right = False
        left = True
        Chart.chart.itemconfigure(x,state=NORMAL)
        Chart.chart.itemconfigure(x,image=heroleftstand)
        for i in range(1,11):
                Chart.chart.move(x,-1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroleftwalk1)
        for i in range(1,11):
                Chart.chart.move(x,-1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroleftwalk2)
        for i in range(1,11):
                Chart.chart.move(x,-1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=heroleftstand)
    def moveright(x):
        global up
        global down
        global left
        global right
        right = True
        up = False
        down = False
        left = False
        Chart.chart.itemconfigure(x,state=NORMAL)
        Chart.chart.itemconfigure(x,image=herorightstand)
        for i in range(1,11):
                Chart.chart.move(x,1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(x,image=herorightwalk1)
        for i in range(1,11):
                Chart.chart.move(x,1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(1,image=herorightwalk2)
        for i in range(1,11):
                Chart.chart.move(x,1,0)
                Chart.chart.update()
                Chart.chart.after(Chart.cycle_period)
        Chart.chart.itemconfigure(1,image=herorightstand)
    def pause(x):
        for i in range(1,30):
            Chart.chart.move(x,0,0)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period)
    def attack():
        global xx
        global yy
class NPCMove:
    def moveup(x):
        for i in range(1,30):
            Chart.chart.move(x,0,-1)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period)
            Chart.chart.itemconfigure(x,image=(npc)+(x))
    def movedown(x):
        for i in range(1,30):
            Chart.chart.move(x,0,1)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period)
    def moveleft(x):
        for i in range(1,30):
            Chart.chart.move(x,-1,0)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period)
    def moveright(x):
        for i in range(1,30):
            Chart.chart.move(x,1,0)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period)
    def pause(x):
        for i in range(1,30):
            Chart.chart.move(x,0,0)
            Chart.chart.update()
            Chart.chart.after(Chart.cycle_period) 




top.bind(sequence="s",func=lambda x:Move.checkwalldown(hero))
top.bind(sequence="w",func=lambda x:Move.checkwallup(hero))
top.bind(sequence="a",func=lambda x:Move.checkwallleft(hero))
top.bind(sequence="d",func=lambda x:Move.checkwallright(hero))
top.bind(sequence="j",func=lambda x:Item.grab(Key,hero))
top.bind(sequence="k",func=lambda x:Item.discard(Key,hero))

market()

Upvotes: 0

Views: 1481

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386240

You simply omit the scrollbars, and make sure that the scrollregion attribute of the canvas encompasses everything that you draw. You can then call the xview and yview methods programmatically to scroll around.

At the end of this post is a runnable example. Run it, click in the window, then use the cursor keys to move the red square. Notice that when it reaches an edge it will cause the canvas to scroll.

This isn't an example of good coding techniques. I have hard-coded numbers all over the place, but hopefully it illustrates how to programmatically scroll a canvas. The main keys to take away from this are:

  1. You need to define a scrollregion greater than the visible window
  2. You need to set the "units" to 1 if you want to scroll one pixel at a time using this technique
  3. you can call the xview and yview methods to scroll the canvas

This code should work for python 2.x; to get it to work on 3.x you should only need to change the import statement.

import Tkinter as tk
import random

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background="bisque")
        self.canvas = tk.Canvas(self, width=400, height=400)

        # define a larger virtual canvas 
        self.canvas.configure(scrollregion=(-400,-400,400,400), 
                              borderwidth=0, highlightthickness=0,
                              xscrollincrement=1, yscrollincrement=1)

        # arrange the widgets on the screen
        self.canvas.pack(fill="both", expand=True)

        # draw a object that we can move
        self.thing = self.canvas.create_rectangle(-20,-20,20,20, fill="red")

        # draw some random circles, so it's obvious when the canvas scrolls
        for i in range(100):
            x = random.randint(-300, 300)
            y = random.randint(-300, 300)
            radius = random.randint(10, 100)
            self.canvas.create_oval(x,y,x+radius, y+radius)

        # set bindings to move the thing around
        self.canvas.bind("<Left>",  lambda event: self.move(-5, 0))
        self.canvas.bind("<Right>", lambda event: self.move(5, 0))
        self.canvas.bind("<Up>",    lambda event: self.move(0,-5))
        self.canvas.bind("<Down>",  lambda event: self.move(0,5))
        self.canvas.bind("c",       lambda event: self.recenter())

        self.recenter()
        self.canvas.focus_set()

    def recenter(self):
        # center the viewport on the canvas
        # (because we know the window size, we know we want 
        # 50% of the window viewable)
        self.canvas.xview("moveto", "0.25")
        self.canvas.yview("moveto", "0.25")

    def make_visible(self):
        # determine the bounding box of the visible area of the screen
        (cx0,cy0) = (self.canvas.canvasx(0), self.canvas.canvasy(0))
        (cx1,cy1) = (self.canvas.canvasx(self.canvas.cget("width")), 
                     self.canvas.canvasy(self.canvas.cget("height")))

        # determine the bounding box of the thing to be made visible
        (x0,y0,x1,y1) = self.canvas.coords(self.thing)

        # determine how far off the screen the object is
        deltax = x0-cx0 if x0 <= cx0 else x1-cx1 if x1 >= cx1 else 0
        deltay = y0-cy0 if y0 <= cy0 else y1-cy1 if y1 >= cy1 else 0

        # scroll the canvas to make the item visible
        self.canvas.xview("scroll", int(deltax), "units")
        self.canvas.yview("scroll", int(deltay), "units")

    def move(self, deltax, deltay):
        # make sure we don't move beyond our scrollable region
        (x0,y0,x1,y1) = self.canvas.coords(self.thing)
        deltay = 0 if (deltay > 0 and y1 >= 400) else deltay
        deltay = 0 if (deltay < 0 and y0 <= -400) else deltay
        deltax = 0 if (deltax > 0 and x1 >= 400) else deltax
        deltax = 0 if (deltax < 0 and x0 <= -400) else deltax

        # move the item, then scroll it into view
        self.canvas.move(self.thing, deltax, deltay)
        self.make_visible()    

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

Upvotes: 1

Related Questions