Пример #1
0
    def initUI(self):
        self.parent.title("TNN visualization")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self, bg="#000")

        width, height = 500, 500
        canvas.config(width=width, height=height)
        canvas.create_line(400, 0, 0, 400, width=1, fill="#fff")

        data = clusterize_data()

        #for i in range(30):
        #    x, y = randint(1, height), randint(1, height)
        #    canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0")

        min, max = -3, 3
        range_data = max - min
        step = 500.0/range_data

        for d in data:
            x, y = (max - d[0])*step , (max - d[1])*step
            x, y = 500 - x, 500 - y
            canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0")

        canvas.pack(fill=BOTH, expand=1)
Пример #2
0
    def initUI(self):
        self.parent.title("Lines")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        for a in range(0, len(lines)):
            line = lines[a]
            canvas.create_line([line["x1"], line["y1"]],
                               [line["x2"], line["y2"]])

        count = 1
        for i in range(0, 10):
            pathh = nx.dijkstra_path(G, path[i - 1], path[i])
            for a in range(0, len(pathh) - 1):
                line = {}
                resize = 5000
                currentNode = allNodes[pathh[a]]
                nextNode = allNodes[pathh[a + 1]]
                left = 44.7240
                bottom = 48.7435
                line["y1"] = 500 - int(
                    (float(currentNode["h"]) - bottom) * resize)
                line["x1"] = int((float(currentNode["w"]) - left) * resize)
                line["y2"] = 500 - int(
                    (float(nextNode["h"]) - bottom) * resize)
                line["x2"] = int((float(nextNode["w"]) - left) * resize)
                canvas.create_line([line["x1"], line["y1"]],
                                   [line["x2"], line["y2"]],
                                   fill="red",
                                   width=count)
            count = count + 1

        canvas.pack(fill=BOTH, expand=1)
Пример #3
0
class CanvasFrame(Frame):
    
    def initializeCanvas(self):
        self.canvas = Canvas(self.master, width=200, height=100)
        self.canvas.pack()
        self.pack()
        
    def setup_timer(self):
        self.x = 10
        self.y = 10
        self.timer_tick()
        
        
    def timer_tick(self):
        self.canvas.delete('all')
        self.canvas.create_line(self.x, self.y, 50, 50)
        self.x = self.x + 1
        self.y = self.y + 2
        print 'in loop'
        print self.x
        print self.y
        self.master.after(1000, self.timer_tick)
        
    
    def __init__(self):
        Frame.__init__(self, Tk())
        self.pack()
        self.initializeCanvas()
        self.setup_timer()
Пример #4
0
    def __init__(self):
        canvas = Canvas(self.root, width=220, height=220)

        corner1 = self.corner1
        corner2 = self.corner2

        canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\
                           fill = "white", width = 3)
        center = self.centerPoint()

        def createTickMark(angle, dFromCenter, length, mark):
            angle -= 90.0
            rads = radians(angle)
            p1 = center.offsetByVector(rads, dFromCenter)
            p2 = center.offsetByVector(rads, dFromCenter + length)
            mark(p1, p2)

        sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y)
        lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\
                                                    fill = 'red', width=3)

        for angle in range(0, 360, 6):
            createTickMark(angle, 90, 9, sm_Tick)

        for angle in range(0, 360, 30):
            createTickMark(angle, 80, 19, lg_Tick)

        for angle in range(0, 360, 90):
            createTickMark(angle, 60, 10, sm_Tick)

        canvas.pack()
        self.root.wm_title("Relógio Analógico")

        self.updateClock(canvas)
Пример #5
0
def plot(text, words, rowheight=15, rowwidth=800):
    """
    Generate a lexical dispersion plot.

    @param text: The source text
    @type text: C{list} or C{enum} of C{str}
    @param words: The target words
    @type words: C{list} of C{str}
    @param rowheight: Pixel height of a row
    @type rowheight: C{int}
    @param rowwidth: Pixel width of a row
    @type rowwidth: C{int}

    """
    canvas = Canvas(width=rowwidth, height=rowheight*len(words))
    text = list(text)
    scale = float(rowwidth)/len(text)
    position = 0
    for word in text:
        for i in range(len(words)):
            x = position * scale
            if word == words[i]:
                y = i * rowheight
                canvas.create_line(x, y, x, y+rowheight-1)
        position += 1
    canvas.pack()
    canvas.mainloop()
Пример #6
0
    def initUI(self):
        self.parent.title("TNN visualization")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self, bg="#000")

        width, height = 500, 500
        canvas.config(width=width, height=height)
        canvas.create_line(400, 0, 0, 400, width=1, fill="#fff")

        data = clusterize_data()

        #for i in range(30):
        #    x, y = randint(1, height), randint(1, height)
        #    canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0")

        min, max = -3, 3
        range_data = max - min
        step = 500.0 / range_data

        for d in data:
            x, y = (max - d[0]) * step, (max - d[1]) * step
            x, y = 500 - x, 500 - y
            canvas.create_oval(x, y, x + 4, y + 4, outline="#0f0", fill="#0f0")

        canvas.pack(fill=BOTH, expand=1)
Пример #7
0
    def __init__(self):
        canvas = Canvas(self.root, width=220, height=220)
        
        #Get the corners of the circle
        corner1 = self.corner1
        corner2 = self.corner2
        
        canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\
                           fill = "white", width = 3)
        center = self.centerPoint()

        def createTickMark(angle, dFromCenter, length, mark):
            angle -= 90.0
            rads = radians(angle)
            p1 = center.offsetByVector(rads, dFromCenter)
            p2 = center.offsetByVector(rads, dFromCenter + length)
            mark(p1, p2)
        #mark is meant to be one of the below lambdas
        sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y)
        lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\
                                                    fill = 'red', width=3)
        #Create minute tick marks
        for angle in range(0, 360, 6):
            createTickMark(angle, 90, 9, sm_Tick)
        #Create hour tick marks 
        for angle in range(0, 360, 30):
            createTickMark(angle, 80, 19, lg_Tick)
        #Create extra marks every 3 hours
        for angle in range(0, 360, 90):
            createTickMark(angle, 60, 10, sm_Tick)

        canvas.pack()
        self.root.wm_title("Clock")
        #Prepare the code to be run in the main loop   
        self.updateClock(canvas)
Пример #8
0
def draw(sequence):
    screen = Tk()
    w = Canvas(screen, width=480, height = 480)
    w.pack()

    w.create_oval(80,80,160,160,fill="green") 
    w.create_oval(80 +120,80,160 +120,160, fill="green")
    w.create_oval(80 +240,80,160 +240,160, fill="green")
    w.create_oval(80,80 +120,160,160+120,fill="green") 
    w.create_oval(80 +120,80 +120,160 +120,160+120, fill="green")
    w.create_oval(80 +240,80+120,160 +240,160+120, fill="green")
    w.create_oval(80,80 +240,160,160+240,fill="green") 
    w.create_oval(80 +120,80 +240,160 +120,160+240, fill="green")
    w.create_oval(80 +240,80+240,160 +240,160+240, fill="green")
   
    
    pos_dict = {"1":(120,120), "2":(240,120), "3":(360,120), "4":(120,240), "5":(240,240), "6":(360,240), "7":(120,360), "8":(240,360), "9":(360,360)}

    for i in range(len(sequence)-1):
        x1 = pos_dict[sequence[i]][0]
        y1 = pos_dict[sequence[i]][1]
        x2 = pos_dict[sequence[i+1]][0]
        y2 = pos_dict[sequence[i+1]][1]
        w.create_line(x1,y1,x2,y2,arrow="last",fill="red",width="5")

    mainloop()
Пример #9
0
class bootWindow:
    def __init__(self, parent):
        logging.info("Host IP: " +get_ip())
        self.screen = Canvas(parent, bg=black, height=480, width=320)
        self.screen.place(x=0,y=0)
        Testline = self.screen.create_line(160, 0, 160, 480, fill=red)
        Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red)
        self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG"))
        self.imglabel = Label(self.screen, image=self.img).place(x=160, y=150, anchor="center")

        self.text = self.screen.create_text(160,270 , text="Loading, Please wait...", fill=white, font=(textFont, 13))

        self.p = ttk.Progressbar(self.screen, orient="horizontal", length=200, mode='determinate')
        self.p.place(x=160, y=300, anchor="center")
        # LOAD ALL THE STUFF!!
        parent.update()
        self.p.step(10)
        parent.update()
        #time.sleep(1)
        self.p.step(10)
        parent.update()
        #time.sleep(1)
        self.p.step(30)
        parent.update()
        time.sleep(1)
        self.screen.destroy()
        self.p.destroy()
    def hide(self):
        pass
    def show(self):
        pass
    def update(self):
        pass
    def __del__(self):
        pass
Пример #10
0
def plot(text, words, rowheight=15, rowwidth=800):
    """
    Generate a lexical dispersion plot.

    @param text: The source text
    @type text: C{list} or C{enum} of C{str}
    @param words: The target words
    @type words: C{list} of C{str}
    @param rowheight: Pixel height of a row
    @type rowheight: C{int}
    @param rowwidth: Pixel width of a row
    @type rowwidth: C{int}

    """
    canvas = Canvas(width=rowwidth, height=rowheight * len(words))
    text = list(text)
    scale = float(rowwidth) / len(text)
    position = 0
    for word in text:
        for i in range(len(words)):
            x = position * scale
            if word == words[i]:
                y = i * rowheight
                canvas.create_line(x, y, x, y + rowheight - 1)
        position += 1
    canvas.pack()
    canvas.mainloop()
Пример #11
0
    def init_ui(self):
        """
        """
        self.parent.title("Worm")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)

        # horizontal lines
        this_row_height = 0
        for row in range(0, self.grid_width - 1):
            this_row_height += self.row_height
            canvas.create_line(0, this_row_height, self.width, this_row_height)

        # vertical lines
        this_column_width = 0
        for column in range(0, self.grid_height-1):
            this_column_width += self.col_width
            canvas.create_line(this_column_width, 0, this_column_width, self.height)

        # pop a circle in every box
        for x in range(0, self.grid_width):
            for y in range(0, self.grid_height):
                self.add_circle(canvas, x, y)

        canvas.pack(fill=BOTH, expand=1)
Пример #12
0
class gridDisplay(Frame):
    def __init__(self, parent, board):
        """
        Initialize an instance of the board within the TKinter hierarchy. Draws the game grid and fills it in
        with the current state of the board as passed into it by the displayBoard method. Numbers part of the 
        goal configuration are displayed in blue, the rest in black.
        """
        Frame.__init__(self, parent) 
        self.parent = parent 
        self.board = board
        self.pack(fill=BOTH)
        self.canvas = Canvas(self, width = WIDTH, height = HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)

        for i in xrange(4):
            color = "red" if (i == 0 or i == 3) else "gray" #Color the grid boundaries red.
            x0 = x1 = MARGIN + i * SIDE
            y0 = MARGIN
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)
            self.canvas.create_line(y0, x0, y1, x1, fill=color)

        for i in xrange(3):
            for j in xrange(3):
                answer = self.board[i][j] #Current state of board at i,j
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    original = goalConfiguration[i][j] #Goal state of board at i, j
                    color = "blue" if answer == original else "black" #Number printed in blue if part of goal state, black if not.
                    self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color)
Пример #13
0
def xGC_skew(seq, window = 1000, zoom = 100,
                         r = 300, px = 100, py = 100):
    """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!)."""
    from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \
                        VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y
    yscroll = Scrollbar(orient = VERTICAL)
    xscroll = Scrollbar(orient = HORIZONTAL)
    canvas = Canvas(yscrollcommand = yscroll.set,
                    xscrollcommand = xscroll.set, background = 'white')
    win = canvas.winfo_toplevel()
    win.geometry('700x700')

    yscroll.config(command = canvas.yview)
    xscroll.config(command = canvas.xview)
    yscroll.pack(side = RIGHT, fill = Y)
    xscroll.pack(side = BOTTOM, fill = X)
    canvas.pack(fill=BOTH, side = LEFT, expand = 1)
    canvas.update()

    X0, Y0 = r + px, r + py
    x1, x2, y1, y2 = X0 - r, X0 + r, Y0 -r, Y0 + r

    ty = Y0
    canvas.create_text(X0, ty, text = '%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq)))
    ty +=20
    canvas.create_text(X0, ty, text = 'GC %3.2f%%' % (GC(seq)))
    ty +=20
    canvas.create_text(X0, ty, text = 'GC Skew', fill = 'blue')
    ty +=20
    canvas.create_text(X0, ty, text = 'Accumulated GC Skew', fill = 'magenta')
    ty +=20
    canvas.create_oval(x1,y1, x2, y2)

    acc = 0
    start = 0
    for gc in GC_skew(seq, window):
        r1 = r
        acc+=gc
        # GC skew
        alpha = pi - (2*pi*start)/len(seq)
        r2 = r1 - gc*zoom
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1,y1,x2,y2, fill = 'blue')
        # accumulated GC skew
        r1 = r - 50
        r2 = r1 - acc
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1,y1,x2,y2, fill = 'magenta')

        canvas.update()
        start += window

    canvas.configure(scrollregion = canvas.bbox(ALL))
Пример #14
0
def xGC_skew(seq, window=1000, zoom=100,
                         r=300, px=100, py=100):
    """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!)."""
    from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \
                        VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y
    yscroll = Scrollbar(orient=VERTICAL)
    xscroll = Scrollbar(orient=HORIZONTAL)
    canvas = Canvas(yscrollcommand=yscroll.set,
                    xscrollcommand=xscroll.set, background='white')
    win = canvas.winfo_toplevel()
    win.geometry('700x700')

    yscroll.config(command=canvas.yview)
    xscroll.config(command=canvas.xview)
    yscroll.pack(side=RIGHT, fill=Y)
    xscroll.pack(side=BOTTOM, fill=X)
    canvas.pack(fill=BOTH, side=LEFT, expand=1)
    canvas.update()

    X0, Y0 = r + px, r + py
    x1, x2, y1, y2 = X0 - r, X0 + r, Y0 - r, Y0 + r

    ty = Y0
    canvas.create_text(X0, ty, text='%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq)))
    ty += 20
    canvas.create_text(X0, ty, text='GC %3.2f%%' % (GC(seq)))
    ty += 20
    canvas.create_text(X0, ty, text='GC Skew', fill='blue')
    ty += 20
    canvas.create_text(X0, ty, text='Accumulated GC Skew', fill='magenta')
    ty += 20
    canvas.create_oval(x1, y1, x2, y2)

    acc = 0
    start = 0
    for gc in GC_skew(seq, window):
        r1 = r
        acc += gc
        # GC skew
        alpha = pi - (2*pi*start)/len(seq)
        r2 = r1 - gc*zoom
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1, y1, x2, y2, fill='blue')
        # accumulated GC skew
        r1 = r - 50
        r2 = r1 - acc
        x1 = X0 + r1 * sin(alpha)
        y1 = Y0 + r1 * cos(alpha)
        x2 = X0 + r2 * sin(alpha)
        y2 = Y0 + r2 * cos(alpha)
        canvas.create_line(x1, y1, x2, y2, fill='magenta')

        canvas.update()
        start += window

    canvas.configure(scrollregion=canvas.bbox(ALL))
Пример #15
0
class Track:
    """ operates with list of satellites
    
    it can read data about satellites from file, from url, display satellites

    """
    def __init__(self):
        # loading images:
        img = Image.open('map.jpg')
        self.map_img = ImageTk.PhotoImage(img)
        img = Image.open('sat.png').convert("RGBA")
        self.sat_img = ImageTk.PhotoImage(img)
        
        self.anim = Canvas(width = 1024, height = 513)
        self.anim.create_image((0,0), anchor = NW, image = self.map_img)
        
        self.satellites = []    # list of satelites loaded from TLE
        self.draw_sats = []     # indices of desired satellites, and their
                                # canvas ID, for animation
    def load_local(self, file_name):
        fp = open(file_name, 'r')
        line = fp.readline()
        print "load"
        while line > '':
            title = line
            l1 = fp.readline()
            l2 = fp.readline()
            tle_data = TLE(title, l1, l2)
            sat = Satellite(tle_data, datetime.today())
            self.satellites.append(sat)
            line = fp.readline()

    def load_url(self, url, file_name):
        # will be improved later,,, now just downloading txt
        # and writes it to file
        buff = urllib2.urlopen(url)
        fp = open(file_name, 'rw')
        fp.write(buff.read())
    
    def update_satellites(self, dt):
        """ recalculate data about satellites """
        for (index, _id) in self.draw_sats:
            self.satellites[index].update(dt)
#        for sat in self.satellites:
#            sat.update(15)
    
    def add_satellite(self, index):
        # index will be taken from GUI,,,aditional images can be added
        _id = self.anim.create_image(self.satellites[index].map_coords, 
                                     image = self.sat_img)
        self.draw_sats.append((index, _id)) # better use dictionaries
        # testing:
        self.satellites[index].get_coords()
        self.anim.create_line(self.satellites[index].trajectory)
    def draw(self):
        """updates position of the satellites on the canvas"""
        for (index, _id) in self.draw_sats:
            self.anim.coords(_id, self.satellites[index].map_coords)
Пример #16
0
	def initUI(self):
		self.parent.title("Shapes")
		self.pack(fill=BOTH, expand=1)
		
		canvas = Canvas(self)
		canvas.create_oval(40, 10, 110, 80, outline="black", width=2)
		canvas.create_line(75, 80, 75, 180, width=2)		

		canvas.pack(fill=BOTH, expand=1)
Пример #17
0
    def initUI(self):
        self.parent.title("Shapes")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_oval(40, 10, 110, 80, outline="black", width=2)
        canvas.create_line(75, 80, 75, 180, width=2)

        canvas.pack(fill=BOTH, expand=1)
Пример #18
0
 def layout(self):
     canvas = Canvas(self.Widget, width=400, height=10)
     canvas.create_line(10, 2, 400, 2, fill='black', tags="line")
     self.rowindex = self.rowindex + 1
     canvas.grid(row=self.rowindex, column=1, columnspan=4)
     lblTarget = Label(self.Widget,
                       text=self.conf.get("TargetDeviceName", "title",
                                          "目标设备"),
                       font=self.fontSize)
     lblTarget.grid(row=self.rowindex, column=1, columnspan=4)
     lblTargetW = Label(self.Widget,
                        text=self.conf.get("TargetDeviceName", "width",
                                           "宽度(px)"),
                        font=self.fontSize)
     self.rowindex = self.rowindex + 1
     lblTargetW.grid(row=self.rowindex, column=1)
     entryTargetW = Entry(self.Widget, width=10, font=self.fontSize)
     entryTargetW.grid(row=self.rowindex, column=2)
     self.entryTargetW = entryTargetW
     lblTargetH = Label(self.Widget,
                        text=self.conf.get("TargetDeviceName", "width",
                                           "高度(px)"),
                        font=self.fontSize)
     lblTargetH.grid(row=self.rowindex, column=3)
     entryTargetH = Entry(self.Widget, width=10, font=self.fontSize)
     entryTargetH.grid(row=self.rowindex, column=4)
     self.entryTargetH = entryTargetH
     fmBox = Frame(self.Widget)
     scrollbar = Scrollbar(fmBox)
     scrollbar.pack(side=RIGHT, fill=Y)
     lb = Listbox(fmBox,
                  yscrollcommand=scrollbar.set,
                  width=25,
                  selectmode=EXTENDED)
     lb.pack(side=LEFT, fill=BOTH)
     scrollbar.config(command=lb.yview)
     self.rowindex = self.rowindex + 1
     fmBox.grid(row=self.rowindex, column=1, columnspan=2)
     self.lb = lb
     fmOper = Frame(self.Widget)
     fmAdd = Frame(fmOper, pady=10)
     btAdd = Button(fmAdd, text="添加", command=self.processAdd)
     btAdd.pack()
     fmDel = Frame(fmOper, pady=10)
     btDel = Button(fmDel, text="删除", command=self.processDel)
     btDel.pack()
     fmAdd.pack(side=TOP)
     fmDel.pack(side=BOTTOM)
     fmOper.grid(row=self.rowindex, column=3)
     canvas = Canvas(self.Widget, width=400, height=10)
     canvas.create_line(10, 2, 400, 2, fill='black', tags="line")
     self.rowindex = self.rowindex + 1
     canvas.grid(row=self.rowindex, column=1, columnspan=4)
     self.readDefDevice()
     return self.rowindex
Пример #19
0
class Screen(Observer):
    def __init__(self,parent,bg="white"):
        self.canvas=Canvas(parent,bg=bg)
        print("parent",parent.cget("width"),parent.cget("height"))

        parent.bind("<Configure>", self.resize)
        self.parent=parent
        self.width=int(self.canvas.cget("width"))
        self.height=int(self.canvas.cget("height"))
        self.models=[]
    def update(self,model):
        if model not in self.models:
            self.models.append(model)
        print("View update")
        signal=model.get_signal()
        self.plot_signal(signal,model.get_color(),model.get_name())


    def plot_signal(self,signal,color,name):
        w,h=self.canvas.winfo_width(),self.canvas.winfo_height()
        width,height=int(w),int(h)
        print(self.canvas.find_withtag("signal"+name))
        if self.canvas.find_withtag("signal"+name) :
            self.canvas.delete("signal"+name)
        if signal and len(signal) > 1:
            if name=="X-Y" :
                plot = [((x+2)*width/4, (2*y/self.m+1)*height/2) for (x, y) in signal]
            else :
                plot = [(x*width, y*height/self.m + height/2) for (x, y) in signal]

            signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal"+name)
        return

    def packing(self) :
        self.canvas.pack(fill="both", expand=1)
    def grid(self,n,m):
        self.n=n
        self.m=m
        w,h=self.canvas.winfo_width(),self.canvas.winfo_height()
        self.width,self.height=int(w),int(h)
        self.canvas.create_line(0,self.height/2.0,self.width-4,self.height/2,arrow="last",tags="line",fill="blue")
        self.canvas.create_line(self.width/2,self.height,self.width/2,5,arrow="last",tags="line",fill="blue")
        step1=self.width/n
        for t in range(1,n):
            x =t*step1
            self.canvas.create_line(x,0,x,self.height,tags="line")
        step=self.height/m
        for t in range(1,m):
            y =t*step
            self.canvas.create_line(0,y,self.width,y,tags="line")
    def resize(self,event):
        self.canvas.delete("line")
        self.grid(self.n,self.m)
        for model in self.models :
            self.plot_signal(model.get_signal(),
                model.get_color(),
                model.get_name())
Пример #20
0
 def initUI(self, n, theta, maxPrm, minPrm):
     self.parent.title("Umbrella")
     self.pack(fill=BOTH, expand=1)
     canvas = Canvas(self, bg="white")
     # ===> CANVAS CROSS MARKERS
     # canvas.create_line(0, 0, self.width, self.height)
     # canvas.create_line(self.width, 0, 0, self.height)
     # canvas.pack(fill=BOTH, expand=1)
     self.visualizeLines(canvas, n, self.maxCenter, theta, maxPrm)
     self.visualizeLines(canvas, n, self.minCenter, theta, minPrm)
     # ===> Horizontal Marker
     canvas.create_line(0, self.height / 2, self.width, self.height / 2)
     canvas.pack(fill=BOTH, expand=1)
Пример #21
0
 def initUI(self, n, theta, maxPrm, minPrm):
     self.parent.title("Umbrella")
     self.pack(fill=BOTH, expand=1)
     canvas = Canvas(self, bg="white")
     # ===> CANVAS CROSS MARKERS
     # canvas.create_line(0, 0, self.width, self.height)
     # canvas.create_line(self.width, 0, 0, self.height)
     # canvas.pack(fill=BOTH, expand=1)
     self.visualizeLines(canvas, n, self.maxCenter, theta, maxPrm)
     self.visualizeLines(canvas, n, self.minCenter, theta, minPrm)
     # ===> Horizontal Marker
     canvas.create_line(0, self.height/2, self.width, self.height/2)
     canvas.pack(fill=BOTH, expand=1)
Пример #22
0
class bootWindow:
    def __init__(self, parent):
        logging.info("Host IP: " + get_ip())
        self.screen = Canvas(parent, bg=black, height=480, width=320)
        self.screen.place(x=0, y=0)
        Testline = self.screen.create_line(160, 0, 160, 480, fill=red)
        Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red)
        self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG"))
        self.imglabel = Label(self.screen,
                              image=self.img).place(x=160,
                                                    y=150,
                                                    anchor="center")

        self.text = self.screen.create_text(160,
                                            270,
                                            text="Loading, Please wait...",
                                            fill=white,
                                            font=(textFont, 13))

        self.p = ttk.Progressbar(self.screen,
                                 orient="horizontal",
                                 length=200,
                                 mode='determinate')
        self.p.place(x=160, y=300, anchor="center")
        # LOAD ALL THE STUFF!!
        parent.update()
        self.p.step(10)
        parent.update()
        #time.sleep(1)
        self.p.step(10)
        parent.update()
        #time.sleep(1)
        self.p.step(30)
        parent.update()
        time.sleep(1)
        self.screen.destroy()
        self.p.destroy()

    def hide(self):
        pass

    def show(self):
        pass

    def update(self):
        pass

    def __del__(self):
        pass
Пример #23
0
 def createScale(self):
     "Create a and return a new canvas with scale markers."
     height = float(self.gheight)
     width = 25
     ymax = self.ymax
     scale = Canvas(self, width=width, height=height, background=self.bg)
     opts = {"fill": "red"}
     # Draw scale line
     scale.create_line(width - 1, height, width - 1, 0, **opts)
     # Draw ticks and numbers
     for y in range(0, int(ymax + 1)):
         ypos = height * (1 - float(y) / ymax)
         scale.create_line(width, ypos, width - 10, ypos, **opts)
         scale.create_text(10, ypos, text=str(y), **opts)
     return scale
Пример #24
0
 def createScale(self):
     "Create a and return a new canvas with scale markers."
     height = float(self.gheight)
     width = 25
     ymax = self.ymax
     scale = Canvas(self, width=width, height=height, background=self.bg)
     opts = {'fill': 'red'}
     # Draw scale line
     scale.create_line(width - 1, height, width - 1, 0, **opts)
     # Draw ticks and numbers
     for y in range(0, int(ymax + 1)):
         ypos = height * (1 - float(y) / ymax)
         scale.create_line(width, ypos, width - 10, ypos, **opts)
         scale.create_text(10, ypos, text=str(y), **opts)
     return scale
Пример #25
0
class canvasInterface(interfaceScreen):
    def __init__(self,master,width,height):
        interfaceScreen.__init__(self)
        self.canvas = Canvas(master, width=width, height=height,bg='white')
        self.canvas.grid(row=0,column=1)

    """
    ---------------Interfaz con objeto dibujante---------------------
    """

    def deleteFromCanvas(self,id):
        self.canvas.delete(id)
        pass

    def create_rectangle(self,x1, y1, x2, y2,*arg,**kargs):
        return self.canvas.create_rectangle(x1, y1, x2, y2,*arg,**kargs)
        pass

    def create_line(self,x1, y1, x2,  y2, *args,**kwargs):
        return self.canvas.create_line(x1, y1, x2,  y2, *args,**kwargs)

    def create_text(self,x1, y1,*args,**kargs):
        return self.canvas.create_text(x1, y1,*args,**kargs)

    def scan_mark(self,x,y):
        self.canvas.scan_mark(x, y)
    def scan_dragto(self,x, y, *args,**kwargs):
        self.canvas.scan_dragto(x, y, *args,**kwargs)

    def winfo_height(self):
        return self.canvas.winfo_height()
    def winfo_width(self):
        return self.canvas.winfo_width()
Пример #26
0
class Visualizer(object):

    def __init__(self, toplevel, **kwargs):
        self.toplevel = toplevel
        self.canvas = Canvas(
            self.toplevel, width=600, height=400, background='black'
        )
        self.canvas.pack()
        self._playing_lines = {}

    def add_point(self, phrase, point, color):
        if point in self._playing_lines:
            self.remove_point(phrase, point)
        if point.type == 'Rest':
            return
        if point not in phrase.points:
            return
        px,py, px2,py2 = phrase.get_line(point)
        self._playing_lines[point] = self.canvas.create_line(
            px,py, px2,py2, fill=color
        )

    def remove_point(self, phrase, point):
        if point not in self._playing_lines:
            return
        self.canvas.delete(self._playing_lines[point])
        del self._playing_lines[point]
Пример #27
0
def show_mol( mol):
  from Tkinter import Tk, Canvas, Frame

  app = Tk()
  app.title( "oasa")

  mainFrame = Frame( app)
  mainFrame.pack( fill='both', expand=1)

  paper = Canvas( mainFrame, width=640, height=480, background="white", closeenough=5)
  paper.pack()

  xmin, xmax, ymin, ymax = None,None,None,None
  for a in mol.vertices:
    if xmin == None or a.x < xmin:
      xmin = a.x
    if xmax == None or a.x > xmax:
      xmax = a.x
    if ymin == None or a.y < ymin:
      ymin = a.y
    if ymax == None or a.y > ymax:
      ymax = a.y

  dx = xmax-xmin
  dy = ymax-ymin
  #print "dx", dy, ymax, ymin
  range = min( (600.0/dx, 450.0/dy))/2
  xp = 640-range*dx
  yp = 480-range*dy
  xtrans = lambda xx: range*(xx - xmin)+xp/2
  ytrans = lambda xx: range*(xx - ymin)+yp/2

  for b in mol.edges:
    a1, a2 = b.vertices
    x1 = xtrans( a1.x)
    x2 = xtrans( a2.x)
    y1 = ytrans( a1.y)
    y2 = ytrans( a2.y)
    paper.create_line( x1, y1, x2, y2, fill='black')
    paper.create_text( (x1+x2)/2, (y1+y2)/2, text=str( b.order), fill="#F00")
  for v in mol.vertices: 
    x = xtrans( v.x)
    y = ytrans( v.y)
    #paper.create_oval( x-5, y-5, x+5, y+5, fill="#0F0")
    paper.create_text( x, y, text=v.symbol, fill="#0F0")
  app.mainloop()
Пример #28
0
class Animation:
    def __init__(self):
        root = Tk()
        self.canvas = Canvas(root, height=500, width=500)
        self.canvas.pack()

        self.canvas.create_rectangle(0, 0, 500, 500, fill="#0D4566", outline="#0D4566")  # space
        self.venus = Planet(250, 150, self.canvas, "red")
        self.earth = Planet(250, 100, self.canvas, "green")
        self.sun = Planet(250, 250, self.canvas, "yellow")

        self.start = time.time()
        self.ticks = 0
        self.done = False
        self.timer()
        root.mainloop()

    def rotate_body(self, body, amount):
        theta = math.degrees(amount)

        x = body.x - 250
        y = body.y - 250

        x, y = x * math.cos(theta) - y * math.sin(theta), x * math.sin(theta) + y * math.cos(theta)

        x += 250
        y += 250

        body.move_to(x, y)

        self.canvas.update()

    def timer(self):
        if self.done:
            print "Done after %2.2f seconds!" % (time.time() - self.start)
            return
        self.rotate_body(self.earth, math.pi / 36000 * 13.0)
        self.rotate_body(self.venus, math.pi / 36000 * 8.0)

        self.ticks += 1
        if self.ticks % 2 == 0:
            self.canvas.create_line(self.earth.x, self.earth.y, self.venus.x, self.venus.y, fill="white")
        if self.ticks > 1250:
            self.done = True

        self.canvas.after(5, self.timer)
Пример #29
0
class ResultsTable(Frame):
    """A custom table widget which displays words alongside the users guesses"""
    def __init__(self, parent, width=400, height=200):

        Frame.__init__(self, parent)
        self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF")
        self.canvas.configure(bd=2, relief=SUNKEN)
        self.canvas.pack(side=LEFT)
        self.centre_line = self.canvas.create_line(0, 0, 0, 0)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)
        scrollbar.configure(command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0,                               width, height))
        self.width=width
        self.height_in_lines = height/18
        self.item_count = 0
        self.font = ("Helvetica", 12)

    def add_word(self, word):
        """Add a word to the table"""
        top = 20*self.item_count
        if top > 200:
            #If necessary extend scroll region downwards
            self.canvas.configure(scrollregion=(0, 0, self.width, top+20))
        colour = "#139E1C" if word.isCorrect else "#F30000"
        #Draw the word in the left column
        self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font)
        #Draw the guess in the right column
        self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour)
        #Draw a line to separate this row from those below
        self.canvas.create_line(0, top+19, self.width, top+19)
        #Extend centre line of tablr
        self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2,
                           top+19)
        self.item_count += 1

    def add_list(self, word_list):
        """Add a list to the table"""
        for word in word_list:
            self.add_word(word)

    def clear(self):
        """Clear the table of all words"""
        self.item_count = 0
        self.canvas.delete(ALL)
Пример #30
0
class Lissajou(Observer):
    def __init__(self, parent,subjects,bg="black"):
        self.subjects=subjects
        self.canvas=Canvas(parent,bg=bg)
        self.width = int(self.canvas.cget("width"))
        self.height = int(self.canvas.cget("height"))
        self.signalXY_id = None
        self.canvas.bind("<Configure>", self.resize)
        self.packing()

    def update(self):
        print("Lissajou update")
        self.signalXY_id = self.plot_lissajou()

    def resize(self, event):
        if event:
            self.width=event.width
            self.height=event.height
            self.grid()
            self.update()

    def grid(self, n=10, m=10,color="white"):
        self.canvas.delete("all")
        w,h=self.width,self.height
        width,height=int(w),int(h)
        self.canvas.create_line(n,(height/2.0),width,(height/2.0),arrow="last",fill=color)
        self.canvas.create_line(width/2.0,height,width/2.0,5.0,arrow="last",fill=color)
        stepX=(width)/m*1.0
        stepY=(height)/n*1.0

        for t in range(1,m+1):
            x =t*stepX
            self.canvas.create_line(x,height,x,20,fill=color)

        for t in range(1,n+1):
            y =t*stepY
            self.canvas.create_line(10.0,y,width-10,y,fill=color)

    def plot_lissajou(self,color='green'):
        width,height=int(self.width-12),int(self.height)
        signalXY = self.subjects.getSignalXY()
        if signalXY!=None:
            self.canvas.delete(self.signalXY_id)
        if signalXY and len(signalXY)>1:
            plot=[((x+1)*(width/2)+5, height/2.0*(y+1)) for (x, y) in signalXY]
            signalValue = self.canvas.create_line(plot, fill=color, smooth=1, width=2)
        return signalValue

    def packing(self):
        self.canvas.pack(expand=1, fill='both',side='top')
Пример #31
0
class PRMViewer(object):
    def __init__(self, width=500, height=500, title='PRM', background='tan'):
        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)
        self.width = width
        self.height = height
        self.canvas = Canvas(top, width=self.width, height=self.height, background=background)
        self.canvas.pack()

    def pixel_from_point(self, point):
        (x, y) = point
        # return (int(x*self.width), int(self.height - y*self.height))
        return (x * self.width, self.height - y * self.height)

    def draw_point(self, point, radius=5):
        (x, y) = self.pixel_from_point(point)
        self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill='black')

    def draw_line(self, segment):
        (point1, point2) = segment
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2)

    def draw_arrow(self, point1, point2):
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2, arrow=LAST)

    def draw_rectangle(self, box, width=2, color='brown'):
        (point1, point2) = box
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, width=width)

    def draw_circle(self, center, radius, width=2, color='black'):
        (x1, y1) = self.pixel_from_point(np.array(center) - radius * np.ones(2))
        (x2, y2) = self.pixel_from_point(np.array(center) + radius * np.ones(2))
        self.canvas.create_oval(x1, y1, x2, y2, outline='black', fill=color, width=width)

    def clear(self):
        self.canvas.delete('all')
Пример #32
0
    def initUI(self):
        self.top.title("Let's Play Baduk")
        xy_size = 800

        C = Canvas(self.top, bg="white", height=xy_size, width=xy_size)
        self.C = C

        size = 40

        for x in range(1, 20):
            coord = x * size, 40, x * size, xy_size - 40
            line = C.create_line(coord, fill="black")

            coord = 40, x * size, xy_size - 40, x * size
            line = C.create_line(coord, fill="black")

        C.pack()

        self.clickEvent()
Пример #33
0
class Interface(Frame):
    def __init__(self, master=Tk()):
        Frame.__init__(self, master)
        self.grid()
        self.llbutton = Button(self, text="Linked List", command=self.createLL)
        self.llbutton.grid()
        self.canvas = Canvas(master, bg="white", height=750, width=1000)
        self.canvas.pack()

    def createLL():
        LL.linked_list()
        print "Linked List chosen"

    def drawNode(self, coord, rad, val):
        self.canvas.create_oval((coord[0], coord[1], coord[0], coord[1]),
                                state="normal",
                                width=rad)
        self.canvas.create_text((coord[0], coord[1]), text=val)

    def drawArrow(self, src, dest):

        if src[0] > dest[0]:
            x1 = src[0] - 20
            x2 = dest[0] + 20
        elif src[0] < dest[0]:
            x1 = src[0] + 20
            x2 = dest[0] - 20
        if src[1] > dest[1]:
            y1 = src[1] - 20
            y2 = dest[1] + 20
        elif src[1] < dest[1]:
            y1 = src[1] + 20
            y2 = dest[1] - 20
        self.canvas.create_line(x1,
                                y1,
                                x2,
                                y2,
                                arrowshape="8 10 7",
                                arrow="last")
        dx = dest[0] - src[0]
        dy = dest[1] - dest[0]
        m = dy / dx
        inv = (dx / dy) * -1
Пример #34
0
	def initUI(self):
		self.parent.title("Koch Snowflake")
		self.pack(fill=BOTH, expand=1)

		c_width, c_height = 600, 600
		inverted = getBoolean()

		points = int(raw_input("Number of corners for starting shape (greater than 1):"))
		start_x, start_y = drawShape(points, c_height, c_width)

		temp_x=[]
		temp_y=[]
		
		canvas=Canvas(self)
		x, y = tip_generator(start_x, start_y, temp_x, temp_y, inverted)
		if len(x)>2:
			for i in range(0, len(x)-1):		
				canvas.create_line(x[i], y[i], x[i+1], y[i+1], fill="blue", width = 2)
			canvas.pack(fill=BOTH, expand=1)
Пример #35
0
	def setup(self):
		self.parent.title(self.TITLE)
		self.pack(fill=BOTH, expand=1)
		canvas = Canvas(self)
		canvas.create_rectangle(self.ORIGIN_X, self.ORIGIN_Y, 
			self.ORIGIN_X + self.BLOCK_W, 
			self.ORIGIN_Y + self.BLOCK_H,
			fill=self.ORIGIN_FILL)
		canvas.create_line(0, self.ORIGIN_Y + (self.BLOCK_H/2),
			self.ORIGIN_X, self.ORIGIN_Y + (self.BLOCK_H/2),
			fill=self.ORIGIN_FILL,
			width=3.0)
		self.counter = canvas.create_text(
			self.COUNTER_X, 
			self.COUNTER_Y,
			anchor=NW)
		canvas.pack(fill=BOTH, expand=1)
		self.canvas = canvas
		self.addHonestNode()
		self.after(self.DELAY, self.update)
Пример #36
0
  def start_gui(self):
    from Tkinter import Tk, Canvas

    root = Tk()
    root.title('Compass Heading')
    canvas = Canvas(root, width=300, height=300)
    canvas.pack()

    canvas.create_oval(0, 0, 300, 300, width=2)

    self.canvas = canvas
    self.compassLine = canvas.create_line(150, 150, 150, 10)
    root.mainloop()
Пример #37
0
    def start_gui(self):
        from Tkinter import Tk, Canvas

        root = Tk()
        root.title('Compass Heading')
        canvas = Canvas(root, width=300, height=300)
        canvas.pack()

        canvas.create_oval(0, 0, 300, 300, width=2)

        self.canvas = canvas
        self.compassLine = canvas.create_line(150, 150, 150, 10)
        root.mainloop()
Пример #38
0
class CoordinatePlot(object):
    """
    Shows the distribution of one coordinate of
    a list of solutions in the complex plane.
    """
    def __init__(self, wdw, dim, sols, idx):
        """
        The layout is just a square canvas, of dimension dim.
        The canvas represents the complex plane for the plot of
        the coordinate defined by index idx of the list sols.
        """
        wdw.title('complex coordinate plot')
        self.cnv = Canvas(wdw, width=dim, height=dim)
        self.cnv.pack()
        self.sols = sols
        self.idx = idx
        self.dim = dim
        self.plot()

    def plot(self):
        """
        Plots a coordinate of the list of solutions.
        """
        from phcpy.solutions import coordinates
        dim = self.dim
        self.cnv.create_line(0, dim / 2, dim, dim / 2)  # x coordinate axis
        self.cnv.create_line(dim / 2, 0, dim / 2, dim)  # y coordinate axis
        (realmin, realmax, imagmin, imagmax) = windowsize(self.sols, self.idx)
        dimreal = max(abs(realmin), abs(realmax))
        dimimag = max(abs(imagmin), abs(imagmax))
        factor = dim / 2 - 10  # the origin is at (dim/2, dim/2)
        for sol in self.sols:
            (names, values) = coordinates(sol)
            val = values[self.idx]
            xpt = dim / 2 + (val.real / dimreal) * factor
            ypt = dim / 2 + (val.imag / dimimag) * factor
            self.cnv.create_oval(xpt-3, ypt-3, \
                xpt+3, ypt+3, fill='red')
Пример #39
0
class Interface(Frame):

    def __init__(self,master=Tk()):
        Frame.__init__(self,master)
        self.grid()
        self.llbutton = Button(self,text="Linked List", command = self.createLL)
        self.llbutton.grid()
        self.canvas = Canvas(master,bg="white",height=750,width=1000)
        self.canvas.pack()


    def createLL():
        LL.linked_list()
        print "Linked List chosen"
        
    def drawNode(self,coord,rad,val):
        self.canvas.create_oval((coord[0],coord[1],coord[0],coord[1]),state="normal",width=rad)
        self.canvas.create_text((coord[0],coord[1]),text=val)

    def drawArrow(self,src,dest):

        if src[0] > dest[0]:
            x1 = src[0] - 20
            x2 = dest[0] + 20
        elif src[0] < dest[0]:
            x1 = src[0] + 20
            x2 = dest[0] - 20
        if src[1] > dest[1]:
            y1 = src[1] - 20
            y2 = dest[1] + 20
        elif src[1] < dest[1]:
            y1 = src[1] + 20
            y2 = dest[1] - 20
        self.canvas.create_line(x1,y1,x2,y2,arrowshape="8 10 7", arrow="last")
        dx = dest[0] - src[0]
        dy = dest[1] - dest[0]
        m = dy/dx
        inv = (dx/dy)*-1
Пример #40
0
class CoordinatePlot(object):
    """
    Shows the distribution of one coordinate of
    a list of solutions in the complex plane.
    """
    def __init__(self, wdw, dim, sols, idx):
        """
        The layout is just a square canvas, of dimension dim.
        The canvas represents the complex plane for the plot of
        the coordinate defined by index idx of the list sols.
        """
        wdw.title('complex coordinate plot')
        self.cnv = Canvas(wdw, width=dim, height=dim)
        self.cnv.pack()
        self.sols = sols
        self.idx = idx
        self.dim = dim
        self.plot()

    def plot(self):
        """
        Plots a coordinate of the list of solutions.
        """
        from phcpy.solutions import coordinates
        dim = self.dim
        self.cnv.create_line(0, dim/2, dim, dim/2) # x coordinate axis
        self.cnv.create_line(dim/2, 0, dim/2, dim) # y coordinate axis
        (realmin, realmax, imagmin, imagmax) = windowsize(self.sols, self.idx)
        dimreal = max(abs(realmin), abs(realmax))
        dimimag = max(abs(imagmin), abs(imagmax))
        factor = dim/2 - 10 # the origin is at (dim/2, dim/2)
        for sol in self.sols:
            (names, values) = coordinates(sol)
            val = values[self.idx]
            xpt = dim/2 + (val.real/dimreal)*factor
            ypt = dim/2 + (val.imag/dimimag)*factor
            self.cnv.create_oval(xpt-3, ypt-3, \
                xpt+3, ypt+3, fill='red')
Пример #41
0
class Display:
    def __init__(self, fps=FPS, width=WIDTH, height=HEIGHT,
        board_offset_bottom=BOARD_OFFSET_BOTTOM,
        board_width=BOARD_WIDTH,
        board_height=BOARD_HEIGHT):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.root.destroy)
        self.width = width
        self.height = height
        self.canvas=Canvas(self.root, bg="black",width=width,height=height)
        self.board_width = board_width
        self.board_height = board_height
        self.board_offset_bottom = board_offset_bottom
        self.canvas.pack()
        self.fps = fps
        self.controllers = []
        #For reset
        self.root.bind("<space>", lambda e:self.reset_all())
        self.root.bind("<Escape>", lambda e:self.root.destroy())
    def run(self):
        self.root.after(1000//self.fps, self.loop)
        try:
            self.root.mainloop()
        except KeyboardInterrupt:
            self.root.destroy()
    def loop(self):
        actions = [controller.get_action(self.model) for controller in self.controllers]
        self.model.update(1./self.fps, actions)
        self.draw()
        self.root.after(1000//self.fps, self.loop)
    def draw(self):
        self.canvas.delete('all')
        self.board = self.canvas.create_rectangle(
            self.model.x()-self.board_width/2,
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.board_width/2,
            self.board_offset_bottom+self.height, fill="green")
        self.pendulum = self.canvas.create_line(
            self.model.x(),
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.model.arm_length*math.sin(self.model.alpha()),
            self.board_offset_bottom+self.height-self.board_height-self.model.arm_length*math.cos(self.model.alpha()),
            fill="blue", width=20)
    def attach_model(self, model):
        self.model = model
        self.draw()
    def attach_controller(self, controller):
        self.controllers.append(controller)
    def reset_all(self):
        self.model.randomize()
Пример #42
0
class ResultsTable(Frame):
    
    def __init__(self, parent, width=400, height=200):

        Frame.__init__(self, parent)
        self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF")
        self.canvas.configure(bd=2, relief=SUNKEN)
        self.canvas.pack(side=LEFT)
        self.centre_line = self.canvas.create_line(0, 0, 0, 0)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)
        scrollbar.configure(command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0,                               width, height))
        self.width=width
        self.height_in_lines = height/18
        self.item_count = 0
        self.font = ("Helvetica", 12)

    def add_word(self, word):
        top = 20*self.item_count
        if top > 200:
            self.canvas.configure(scrollregion=(0, 0, self.width, top+20))
        colour = "#139E1C" if word.isCorrect else "#F30000"
        self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font)
        self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour)
        self.canvas.create_line(0, top+19, self.width, top+19)
        self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2,
                           top+19)
        self.item_count += 1

    def add_list(self, word_list):
        for word in word_list:
            self.add_word(word)

    def clear(self):
        self.item_count = 0
        self.canvas.delete(ALL)
Пример #43
0
class View(Observer):
    def __init__(self,parent,subject,bg="white"):
        print("View : __init__")
        Observer.__init__(self)
        self.subject=subject
        self.parent=parent
        self.signal_id=None
        self.canvas=Canvas(parent,bg=bg)
        self.canvas.bind("<Configure>", self.resize)
        self.width=int(self.canvas.cget("width"))
        self.height=int(self.canvas.cget("height"))

    def update(self,subject):
        print("View : update")
        signal=subject.get_signal()
        self.signal_id=self.plot_signal(signal)
    def plot_signal(self,signal,color="red"):
        width,height=self.width,self.height
        if self.signal_id!=None :
            self.canvas.delete(self.signal_id)
        if signal and len(signal)>1:
            plot=[(x*width, height/2.0*(y+1)) for (x, y) in signal]
            self.signal_id=self.canvas.create_line(plot,fill=color,smooth=1,width=3)
        return self.signal_id

    def resize(self, event):
        """
        En cas de reconfiguration de fenetre
        """
        if event:
            self.width = event.width
            self.height = event.height
##            self.width = int(event.widget.cget("width"))
##            self.height = int(event.widget.cget("height"))
##            print("View : resize cget",event.widget.cget("width"),event.widget.cget("height"))
        print("View : resize event",event.width,event.height)
        self.canvas.delete("grid")
        self.plot_signal(self.subject.get_signal())
        self.grid()

    def grid(self, steps=8):
        width,height=self.width,self.height
#        self.canvas.create_line(10,height/2,width,height/2,arrow="last",tags="grid")
#        self.canvas.create_line(10,height-5,10,5,arrow="last",tags="grid")
        step=width/steps*1.
        for t in range(1,steps+2):
            x =t*step
            self.canvas.create_line(x,0,x,height,tags="grid")
            self.canvas.create_line(0,x,width,x,tags="grid")
            self.canvas.create_line(x,height/2-4,x,height/2+4,tags="grid")
    def packing(self) :
        self.canvas.pack(expand=1,fill="both",padx=6)
Пример #44
0
	def draw( self, tree,row=0,col=0):

		self.findCoords(tree)

		self.grid(row=row,column=col,sticky=N+S+E+W)

		xOff, yOff = 50 - self.minX, 50 - self.minY

		self.minX += xOff
		self.maxX += xOff
		self.minY += yOff
		self.maxY += yOff

		canvas = Canvas(self)

		for line in self.linesToDraw:
			((sX,sY),(eX,eY)) = line
			canvas.create_line(sX+xOff,sY+yOff,eX+xOff,eY+yOff)

		for circle in self.circlesToDraw:
			x,y,c = circle
			canvas.create_oval(x+xOff-5,y+yOff-5,x+xOff+5,y+yOff+5,fill=c)

		canvas.grid(row=row,column=col,sticky=N+S+E+W)
Пример #45
0
    def __init__(self):
        canvas = Canvas(self.root, width=220, height=220)

        #Get the corners of the circle
        corner1 = self.corner1
        corner2 = self.corner2

        canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\
                           fill = "white", width = 3)
        center = self.centerPoint()

        def createTickMark(angle, dFromCenter, length, mark):
            angle -= 90.0
            rads = radians(angle)
            p1 = center.offsetByVector(rads, dFromCenter)
            p2 = center.offsetByVector(rads, dFromCenter + length)
            mark(p1, p2)

        #mark is meant to be one of the below lambdas
        sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y)
        lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\
                                                    fill = 'red', width=3)
        #Create minute tick marks
        for angle in range(0, 360, 6):
            createTickMark(angle, 90, 9, sm_Tick)
        #Create hour tick marks
        for angle in range(0, 360, 30):
            createTickMark(angle, 80, 19, lg_Tick)
        #Create extra marks every 3 hours
        for angle in range(0, 360, 90):
            createTickMark(angle, 60, 10, sm_Tick)

        canvas.pack()
        self.root.wm_title("Clock")
        #Prepare the code to be run in the main loop
        self.updateClock(canvas)
Пример #46
0
    def initUI(self):
        self.parent.title("Lines")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_line(15, 25, 200, 25)
        canvas.create_line(300, 35, 300, 200, dash=(4, 2))
        canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)

        canvas.pack(fill=BOTH, expand=1)
Пример #47
0
    def initUI(self):
        self.parent.title("Lines")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_line(15, 25, 200, 25)
        canvas.create_line(300, 35, 300, 200, dash=(4,2))
        canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)

        canvas.pack(fill=BOTH, expand=1)
Пример #48
0
class App(Frame):
    """Tkinter App."""

    def __init__(self, parent, queue):
        """Init Tkinter app."""
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.wm_attributes('-type', 'dialog')

        self.queue = queue
        self.initUI()
        self.worker()

    def initUI(self):
        """Init UI."""
        self.parent.title('PySnake')
        self.canvas = Canvas(self.parent, width=500, height=300, bg='black')
        self.canvas.pack()

        self.score = self.canvas.create_text(30, 270, anchor=W, fill='blue', text='Score: 0')
        self.food = self.canvas.create_rectangle(0, 0, 0, 0, fill='white')
        self.snake = self.canvas.create_line((0, 0), (0, 0), fill='green', width=10)

    def worker(self):
        try:
            while True:
                job = self.queue.get_nowait()
                if job.has_key('snake'):
                    #self.snake = self.canvas.create_line(*job['snake'], fill='green', width=10)
                    points = [x for point in job['snake'] for x in point]
                    self.canvas.coords(self.snake, *points)
                elif job.has_key('food'):
                    x, y = job['food']
                    self.canvas.coords(self.food, (x - 5), (y - 5), (x + 5), (y + 5))
                elif job.has_key('score'):
                    self.canvas.itemconfigure(self.score, text='Score: {}'.format(job['score']))
                elif job.has_key('quit'):
                    self.parent.quit()
                self.queue.task_done()
        except Queue.Empty:
            pass
        self.after(50, self.worker)
Пример #49
0
class App(Frame):
    """Tkinter App."""

    def __init__(self, parent, queue):
        """Init Tkinter app."""
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.wm_attributes("-type", "dialog")

        self.queue = queue
        self.initUI()
        self.worker()

    def initUI(self):
        """Init UI."""
        self.parent.title("PySnake")
        self.canvas = Canvas(self.parent, width=500, height=300, bg="black")
        self.canvas.pack()

        self.score = self.canvas.create_text(30, 270, anchor=W, fill="blue", text="Score: 0")
        self.food = self.canvas.create_rectangle(0, 0, 0, 0, fill="white")
        self.snake = self.canvas.create_line((0, 0), (0, 0), fill="green", width=10)

    def worker(self):
        try:
            while True:
                job = self.queue.get_nowait()
                if job.has_key("snake"):
                    # self.snake = self.canvas.create_line(*job['snake'], fill='green', width=10)
                    points = [x for point in job["snake"] for x in point]
                    self.canvas.coords(self.snake, *points)
                elif job.has_key("food"):
                    x, y = job["food"]
                    self.canvas.coords(self.food, (x - 5), (y - 5), (x + 5), (y + 5))
                elif job.has_key("score"):
                    self.canvas.itemconfigure(self.score, text="Score: {}".format(job["score"]))
                elif job.has_key("quit"):
                    self.parent.quit()
                self.queue.task_done()
        except Queue.Empty:
            pass
        self.after(50, self.worker)
Пример #50
0
class Clock(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.parent = parent
		self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
		self.initTime()
		self.draw()
		self.onTimer()

	def initTime(self):
		self.hourHand = time.localtime().tm_hour % 12 * 5
		self.minuteHand = time.localtime().tm_min
		self.secondHand = time.localtime().tm_sec

	def draw(self):
		self.pack(fill=BOTH, expand=1)		
		radius = 300
		x, y = 50, 50		
		centerX, centerY = 180, 180
		hourX = centerX + 0.3 * radius/2.0 * math.cos(self.toRadian(self.hourHand))
		hourY = centerY + 0.3 * radius/2.0 * math.sin(self.toRadian(self.hourHand))
		minuteX = centerX + 0.6 * radius/2.0 * math.cos(self.toRadian(self.minuteHand))
		minuteY = centerY + 0.6 * radius/2.0 * math.sin(self.toRadian(self.minuteHand))
		secondX = centerX + 0.75 * radius/2.0 * math.cos(self.toRadian(self.secondHand))
		secondY = centerY + 0.75 * radius/2.0 * math.sin(self.toRadian(self.secondHand))		
		self.canvas.create_oval(x, y, radius, radius, outline="black", fill="black")
		self.canvas.create_line(centerX, centerY, hourX, hourY, width=3, fill="green")
		self.canvas.create_line(centerX, centerY, minuteX, minuteY, width=3, fill="green")
		self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red")
		self.canvas.pack(fill=BOTH, expand=1)

	def toRadian(self, x):
		return (x * math.pi/30.0) - (math.pi/2.0)
		
	def onTimer(self):
		self.tick()
		self.canvas.delete(ALL)
		self.draw()
		self.after(DELAY, self.onTimer)
		
	def tick(self):
		self.secondHand = (self.secondHand + 1) % 60
		if self.secondHand == 0:
			self.minuteHand = (self.minuteHand + 1) % 60
			if self.minuteHand == 0:
				self.hourHand = (self.hourHand + 5) % 60
Пример #51
0
class Screen(Observer):
    def __init__(self,parent,bg="white"):
        self.canvas=Canvas(parent,bg=bg)
        print("parent",parent.cget("width"),parent.cget("height"))
        self.magnitude=Scale(parent,length=250,orient="horizontal",
                         label="Magnitude", sliderlength=20,
                         showvalue=0,from_=0,to=5,
                         tickinterval=25)
    def update(self,model):
        print("View update")
        signal=model.get_signal()
        self.plot_signal(signal)

    def get_magnitude(self):
        return self.magnitude
        
    def plot_signal(self,signal,color="red"):
        w,h=self.canvas.cget("width"),self.canvas.cget("height")
        width,height=int(w),int(h)
#        print(self.canvas.find_withtag("signal"))
        if self.canvas.find_withtag("signal") :
            self.canvas.delete("signal")
        if signal and len(signal) > 1:
            plot = [(x*width, height/2.0*(y+1)) for (x, y) in signal]
            signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal")
        return

    def grid(self, steps):
        w,h=self.canvas.cget("width"),self.canvas.cget("height")
        width,height=int(w),int(h)
        self.canvas.create_line(10,height/2,width,height/2,arrow="last")
        self.canvas.create_line(10,height-5,10,5,arrow="last")
        step=(width-10)/steps*1.
        for t in range(1,steps+2):
            x =t*step
            self.canvas.create_line(x,height/2-4,x,height/2+4)

    def packing(self) :
        self.canvas.pack()
        self.magnitude.pack()
Пример #52
0
    def initUI(self):
        self.parent.title("Lines")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        for a in range(0, len(lines)):
            line = lines[a]
            canvas.create_line([line["x1"], line["y1"]],
                               [line["x2"], line["y2"]])

        count = 0
        for path in paths:
            for a in range(0, len(path) - 1):
                line = {}
                resize = 5000
                currentNode = allNodes[path[a]]
                nextNode = allNodes[path[a + 1]]
                left = 44.7240
                bottom = 48.7435
                line["y1"] = 500 - int(
                    (float(currentNode["h"]) - bottom) * resize)
                line["x1"] = int((float(currentNode["w"]) - left) * resize)
                line["y2"] = 500 - int(
                    (float(nextNode["h"]) - bottom) * resize)
                line["x2"] = int((float(nextNode["w"]) - left) * resize)
                if count == minPathId:
                    canvas.create_line([line["x1"], line["y1"]],
                                       [line["x2"], line["y2"]],
                                       fill="red",
                                       width=4)
                else:
                    canvas.create_line([line["x1"], line["y1"]],
                                       [line["x2"], line["y2"]],
                                       fill="blue",
                                       width=1)
            count = count + 1

        canvas.pack(fill=BOTH, expand=1)
Пример #53
0
def screen_draw():
    global window, canvas_frame, canvas_play, canvas_play1, canvas_play2, canvas_future, level, point, max_point, canvas_pause
    level = 1
    point = 0
    max_point = 0
    canvas_frame = Canvas(window)  #,bg='red')
    canvas_frame.place(x=0, y=0, relwidth=1.0, relheight=1.0)
    global frame1, frame2
    frame1 = Frame(window)
    frame2 = Frame(window)
    frame1.place(x=0, y=0, width=300, height=600)
    frame2.place(x=0, y=0, width=300, height=600)
    canvas_play1 = Canvas(frame1, bg='#000000')
    canvas_play1.place(x=0, y=0, width=300, height=600)
    for x in range(1, 10):
        for y in range(1, 20):
            canvas_play1.create_line(30 * x, 0, 30 * x, 600,
                                     fill='#111111')  #,tag='play')
            canvas_play1.create_line(0, 30 * y, 300, 30 * y,
                                     fill='#111111')  #,tag='play')
    canvas_play2 = Canvas(frame2, bg='#000000')
    canvas_play2.place(x=0, y=0, width=300, height=600)
    for x in range(1, 10):
        for y in range(1, 20):
            canvas_play2.create_line(30 * x, 0, 30 * x, 600, fill='#111111')
            canvas_play2.create_line(0, 30 * y, 300, 30 * y, fill='#111111')
    canvas_play = frame2
    canvas_frame.create_text(370,
                             200,
                             font=('Purisa', 24),
                             text='Level',
                             anchor='n')
    canvas_frame.create_text(370,
                             336,
                             font=('Purisa', 24),
                             text='Point',
                             anchor='n')
    canvas_frame.create_text(370,
                             436,
                             font=('Purisa', 24),
                             text='Max',
                             anchor='n')
    canvas_frame.create_text(370,
                             270,
                             text=str(level),
                             font=('', 24),
                             fill='#0000ff',
                             tag='level')
    canvas_frame.create_text(370,
                             400,
                             text=str(point),
                             font=('', 24),
                             fill='#0000ff',
                             tag='point')
    canvas_frame.create_text(370,
                             500,
                             text=str(max_point),
                             font=('', 24),
                             fill='#ff0000',
                             tag='max')
    canvas_future = Canvas(window)  #,bg='#0000ff')
    canvas_future.place(x=310, y=10, width=120, height=120)
    canvas_pause = Canvas(canvas_frame)  #,bg='yellow')
    canvas_pause.place(x=345, y=540, width=50, height=50)
    draw_play()
    canvas_pause.bind('<ButtonPress-1>', event_pause)
Пример #54
0
class Screen(Observer):
    def __init__(self, parent, bg="white"):
        self.menu_bar = MenuBar(parent)
        self.canvas = Canvas(parent, bg=bg, name="screen")
        self.frameControl = Frame(parent)
        self.frameLabelSignals = LabelFrame(self.frameControl,
                                            text="Signaux",
                                            padx=20,
                                            pady=20)
        self.frameLabelMode = LabelFrame(self.frameControl,
                                         text="Mode",
                                         padx=20,
                                         pady=20)
        self.panelControl = ttk.Notebook(self.frameLabelSignals)
        self.checkbox_signalX = Checkbutton(self.frameLabelMode,
                                            text="Signal X")
        self.checkbox_signalY = Checkbutton(self.frameLabelMode,
                                            text="Signal Y")
        self.checkbox_XY = Checkbutton(self.frameLabelMode, text="XY")

        self.panel_control_page = []  # contient les références de mes curseurs

        for p in parent.get_models():
            self.addPage(p.get_name())

    def addPage(self, name):
        page = ttk.Frame(self.panelControl)
        self.panelControl.add(page, text='signal ' + name)

        visible_checkbox = Checkbutton(page, text="Afficher")
        magnitude = Scale(page,
                          length=250,
                          orient="horizontal",
                          label="Amplitude",
                          sliderlength=20,
                          showvalue=0,
                          from_=0,
                          to=5,
                          tickinterval=1,
                          name="magnitudeScale")
        frequency = Scale(page,
                          length=250,
                          orient="horizontal",
                          label="Frequency",
                          sliderlength=20,
                          showvalue=0,
                          from_=0,
                          to=25,
                          tickinterval=5,
                          name="frequencyScale")
        phase = Scale(page,
                      length=250,
                      orient="horizontal",
                      label="Phase",
                      sliderlength=20,
                      showvalue=0,
                      from_=0,
                      to=20,
                      tickinterval=5,
                      name="phaseScale")
        visible_checkbox.pack(fill="x", pady=6)
        magnitude.pack(expand=1, fill="both", pady=6)
        frequency.pack(expand=1, fill="both", pady=6)
        phase.pack(expand=1, fill="both", pady=6)
        self.panel_control_page.append({
            'visible': visible_checkbox,
            'magnitude': magnitude,
            'frequency': frequency,
            'phase': phase
        })

    def update(self, model):
        if type(model) == list:
            for i, m in enumerate(model):
                signal = m.get_signal()
                #self.plot_signal(signal, m.get_color())
                self.plot_signal(m)
        else:
            signal = model.get_signal()
            self.plot_signal(model)
        self.grid(6, 8)

    def get_panel_control_index(self):
        return self.panelControl.index('current')

    def get_canvas(self):
        return self.canvas

    def get_panel_control_page(self):
        return self.panel_control_page

    def get_magnitude(self, index):
        return self.panel_control_page[index]['magnitude']

    def get_frequency(self, index):
        return self.panel_control_page[index]['frequency']

    def get_phase(self, index):
        return self.panel_control_page[index]['phase']

    def get_visible(self, index):
        return self.panel_control_page[index]['visible']

    def get_checkbox_signalX(self):
        return self.checkbox_signalX

    def get_checkbox_signalY(self):
        return self.checkbox_signalY

    def get_checkbox_XY(self):
        return self.checkbox_XY

    def plot_signal(self, model):
        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
        width, height = int(w), int(h)

        signal = model.get_signal()
        name = model.get_name()
        color = model.get_color()

        if self.canvas.find_withtag("signal" + name):
            self.canvas.delete("signal" + name)

        if signal and len(signal) > 1 and model.is_visible():
            plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal]
            self.canvas.create_line(plot,
                                    fill=color,
                                    smooth=1,
                                    width=3,
                                    tags="signal" + name)
            self.canvas.scale("signal" + name, width / 2, height / 2, 1.0,
                              0.25)

    def grid(self, row, col):
        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
        width, height = int(w), int(h)

        if self.canvas.find_withtag("grid"):
            self.canvas.delete("grid")

        # dessin des axes X et Y
        self.canvas.create_line(5,
                                height / 2,
                                width,
                                height / 2,
                                arrow="last",
                                tags=('grid', 'axe-x'))
        self.canvas.create_line(width / 2,
                                height - 5,
                                width / 2,
                                5,
                                arrow="last",
                                tags=('grid', 'axe-y'))

        # dessin des lignes verticales
        for c in range(1, int(row / 2) + 1):
            stepW = width / row
            xd = width / 2 + c * stepW
            xg = width / 2 - c * stepW
            #Creation des lignes verticales
            self.canvas.create_line(xd,
                                    height - 5,
                                    xd,
                                    5,
                                    dash=1,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')  #cote droit
            self.canvas.create_line(xg,
                                    height - 5,
                                    xg,
                                    5,
                                    dash=1,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')  #cote gauche
            #Creation des tirets sur x
            self.canvas.create_line(xd,
                                    height / 2 - 4,
                                    xd,
                                    height / 2 + 4,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            self.canvas.create_line(xg,
                                    height / 2 - 4,
                                    xg,
                                    height / 2 + 4,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')

        # dessin des lignes horizontales
        for r in range(1, int(col / 2) + 1):
            stepH = height / col
            yB = height / 2 + r * stepH
            yH = height / 2 - r * stepH
            #Creation des lignes horizontales
            self.canvas.create_line(5,
                                    yB,
                                    width,
                                    yB,
                                    dash=1,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            self.canvas.create_line(5,
                                    yH,
                                    width,
                                    yH,
                                    dash=1,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            #Creation des tirets sur y
            self.canvas.create_line(width / 2 - 4,
                                    yB,
                                    width / 2 + 4,
                                    yB,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')
            self.canvas.create_line(width / 2 - 4,
                                    yH,
                                    width / 2 + 4,
                                    yH,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')

    def packing(self):
        self.menu_bar.pack(fill='x')
        self.canvas.pack(side=LEFT, expand=1, fill="both", padx=6, pady=6)
        self.panelControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
        self.frameLabelSignals.pack(expand=1, fill="both")
        self.frameLabelMode.pack(expand=1, fill="both")
        self.checkbox_signalX.pack(side=LEFT)
        self.checkbox_signalY.pack(side=LEFT)
        self.checkbox_XY.pack(side=RIGHT)
        self.frameControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
Пример #55
0
class Clock(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.initTime()
        self.draw()
        self.onTimer()

    def initTime(self):
        self.hourHand = time.localtime().tm_hour % 12 * 5
        self.minuteHand = time.localtime().tm_min
        self.secondHand = time.localtime().tm_sec

    def draw(self):
        self.pack(fill=BOTH, expand=1)
        radius = 300
        x, y = 50, 50
        centerX, centerY = 180, 180
        hourX = centerX + 0.3 * radius / 2.0 * math.cos(
            self.toRadian(self.hourHand))
        hourY = centerY + 0.3 * radius / 2.0 * math.sin(
            self.toRadian(self.hourHand))
        minuteX = centerX + 0.6 * radius / 2.0 * math.cos(
            self.toRadian(self.minuteHand))
        minuteY = centerY + 0.6 * radius / 2.0 * math.sin(
            self.toRadian(self.minuteHand))
        secondX = centerX + 0.75 * radius / 2.0 * math.cos(
            self.toRadian(self.secondHand))
        secondY = centerY + 0.75 * radius / 2.0 * math.sin(
            self.toRadian(self.secondHand))
        self.canvas.create_oval(x,
                                y,
                                radius,
                                radius,
                                outline="black",
                                fill="black")
        self.canvas.create_line(centerX,
                                centerY,
                                hourX,
                                hourY,
                                width=3,
                                fill="green")
        self.canvas.create_line(centerX,
                                centerY,
                                minuteX,
                                minuteY,
                                width=3,
                                fill="green")
        self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red")
        self.canvas.pack(fill=BOTH, expand=1)

    def toRadian(self, x):
        return (x * math.pi / 30.0) - (math.pi / 2.0)

    def onTimer(self):
        self.tick()
        self.canvas.delete(ALL)
        self.draw()
        self.after(DELAY, self.onTimer)

    def tick(self):
        self.secondHand = (self.secondHand + 1) % 60
        if self.secondHand == 0:
            self.minuteHand = (self.minuteHand + 1) % 60
            if self.minuteHand == 0:
                self.hourHand = (self.hourHand + 5) % 60
Пример #56
0
class carGUI:

    carDict = {}
    carIDs = []

    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        # Initialize Canvas
        self.canv = Canvas(master)
        self.canv.pack(fill='both', expand=True)

        # Initialize X-Lane
        self.xTop = self.canv.create_line(0,
                                          470,
                                          1000,
                                          470,
                                          fill='black',
                                          tags=('top'))
        self.xBottom = self.canv.create_line(0,
                                             510,
                                             1000,
                                             510,
                                             fill='black',
                                             tags=('left'))

        # Initialize Y-Lane
        self.yLeft = self.canv.create_line(470,
                                           0,
                                           470,
                                           1000,
                                           fill='blue',
                                           tags='right')
        self.yRight = self.canv.create_line(510,
                                            0,
                                            510,
                                            1000,
                                            fill='blue',
                                            tags='bottom')

        # Highlight Intersection
        self.rect = self.canv.create_rectangle(470,
                                               470,
                                               510,
                                               510,
                                               fill='green')

        # Show Regulation Lines
        self.xLimit = self.canv.create_line(470 - 40,
                                            450,
                                            470 - 40,
                                            530,
                                            fill="red")
        self.yLimit = self.canv.create_line(450,
                                            470 - 40,
                                            530,
                                            470 - 40,
                                            fill="red")

        # Create button to begin simulation
        b = Button(text="Start Simluation!", command=self.simClickListener)
        b.pack()

        # Create checkbox to differentiate real world sim from autonomous sim
        self.CheckVar = IntVar()
        self.checkConventional = Checkbutton(text="Conventional System", variable=self.CheckVar, \
            onvalue=1, offvalue=0, height=5)
        self.checkConventional.pack()

        # Create text fields to show first in queue cars
        self.carDisplayX = self.canv.create_text(10,
                                                 10,
                                                 anchor="nw",
                                                 fill="red")
        self.carDisplayY = self.canv.create_text(600,
                                                 10,
                                                 anchor="nw",
                                                 fill="black")

    def drawCar(self, lane, ID):

        if (lane == 1):
            # Draw an X car
            self.rect = self.canv.create_rectangle(0,
                                                   485,
                                                   10,
                                                   495,
                                                   fill='black')
        elif (lane == 2):
            # Draw a Y car
            self.rect = self.canv.create_rectangle(485, 0, 495, 10, fill='red')

        self.canv.addtag_below(self.rect, "HELLO")

        # Register the ID of the car
        self.carIDs.append(ID)
        # Ad the key value pair to the car dictionary for the GUI
        self.carDict[ID] = self.rect

    def moveCars(self, carList, timeInterval):

        self.master.update_idletasks()  # THIS UPDATES THE GUI

        for i in range(0, len(carList)):
            self.canv.move(self.carDict[carList[i].ID],
                           carList[i].velocityX * timeInterval,
                           carList[i].velocityY * timeInterval)

    def highlightCar(self, car, color):
        self.canv.itemconfig(self.carDict[car.ID], fill=color)

    def simClickListener(self):
        from Simulation import simulation as sim
        sim(self)

    def updateCarInformationDisplay(self, car):
        carData = "position X = " + str(car.positionX) + "\nposition Y = " + \
            str(car.positionY) + "\nvelocity X = " + str(car.velocityX) + \
            "\nvelocity Y = " + str(car.velocityY)

        if (car.velocityX > 0):
            self.canv.itemconfig(self.carDisplayX, text=carData)

        else:
            self.canv.itemconfig(self.carDisplayY, text=carData)
Пример #57
0
class ReversiView:
    '''
    Creates window with the reversi board and controls the game using gui.
    '''
    def __init__(self, players, boardSize=8, w=850, h=410):
        '''
        :param w: width of the window
        :param h: height of the window
        '''
        self.root = Tk()
        self.boardSize = boardSize
        self.stone_board = [-1] * self.boardSize
        for row in range(self.boardSize):
            self.stone_board[row] = [-1] * self.boardSize
        self.w = w
        self.h = h
        self.offx = 5
        self.offy = 5
        self.gridw = 410
        self.gridh = 410
        self.gridspacing = 50
        self.ovalDiamPart = 0.8
        self.colors = ["blue", "red"]
        self.root.title("Reversi")

        self.interactive_player_ids = []
        self.interactivePlayers = []

        self.interractivePlayerName = 'Interactive'
        self.possiblePlayers = {
            self.interractivePlayerName: -1,
        }
        for player_name in players.keys():
            self.possiblePlayers[player_name] = players[player_name]

        self.wrong_move = False
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = (ws / 2) - (self.w / 2)
        y = (hs / 2) - (self.h / 2)

        self.root.geometry('%dx%d+%d+%d' % (self.w, self.h, x, y))
        self.draw_game_grid()
        self.draw_game_info_grid()

        self.game_state = GameState.STOPPED

    def set_game(self, game):
        '''
        Sets the game to the GUI.
        '''
        self.game = game

    def set_board(self, board):
        '''
        Sets the game board to the GUI.
        '''
        self.board = board

    def draw_stone(self, x, y, color):
        '''
        Draw stone on position [x,y] in gui
        :param x: x coordinate of the stone
        :param y: y coordinate of the stone
        :param color: 0 for blue, 1 fro red
        '''
        x_coord = (self.gridspacing *
                   x) + (1.0 - self.ovalDiamPart) * self.gridspacing
        y_coord = (self.gridspacing *
                   y) + (1.0 - self.ovalDiamPart) * self.gridspacing
        diameter = self.ovalDiamPart * self.gridspacing
        self.clear_stone(x, y)
        self.stone_board[x][y] = self.grid.create_oval(x_coord,
                                                       y_coord,
                                                       x_coord + diameter,
                                                       y_coord + diameter,
                                                       fill=self.colors[color])

    def clear_stone(self, x, y):
        '''
        Delete stone on position [x,y] from the gui
        :param x: x coordinate of the stone
        :param y: y coordinate of the stone
        '''
        if self.stone_board[x][y] != -1:
            self.grid.delete(self.stone_board[x][y])
            self.stone_board[x][y] = -1

    def draw_game_info_grid(self):
        '''
        Draw control and inform part of game to right side of the window.
        '''
        self.info = Canvas(self.root,
                           height=self.h - self.gridh,
                           width=self.w - self.gridw)
        self.info.pack(side="left")

        label_stones = Label(self.info,
                             text="Current stones:",
                             font=("Helvetica", 10))
        label_stones.grid(row=1, column=0)
        label_max_time = Label(self.info,
                               text="Max time:",
                               font=("Helvetica", 10))
        label_max_time.grid(row=2, column=0)

        label_scale = Label(self.info,
                            text='Game speed [ms]:',
                            font=("Helvetica", 10),
                            foreground='black')
        label_scale.grid(row=5, column=0)

        helv36 = font.Font(family="helvetica", size=16, weight='bold')
        self.scale_var = IntVar()
        scale = Scale(self.info,
                      variable=self.scale_var,
                      command=self.sleep_time_change_handler,
                      from_=0,
                      to=1000,
                      resolution=10,
                      width="15",
                      orient=HORIZONTAL,
                      length="225")
        scale.set(200)
        scale.grid(row=5, column=1, columnspan=3)

        self.button = Button(self.info,
                             text="Play",
                             width="20",
                             height="2",
                             command=self.play_button_click_handler)
        self.button['font'] = helv36
        self.button.grid(row=6, column=0, columnspan=4)

        # labels for num stones, max time of move, etc
        self.label_player_stones = [-1, -1]
        self.label_player_max_time = [-1, -1]
        self.labels_inform = [-1, -1]
        self.labels_player_name = [-1, -1]
        self.option_menus = [-1, -1]
        self.option_menus_vars = [-1, -1]

        for i in range(2):
            self.label_player_stones[i] = Label(self.info,
                                                text='2',
                                                font=("Helvetica", 10),
                                                foreground=self.colors[i])
            self.label_player_stones[i].grid(row=1,
                                             column=2 * (i + 1) - 1,
                                             columnspan=2)

            self.label_player_max_time[i] = Label(self.info,
                                                  text="%.2f [ms]" % 0.0,
                                                  font=("Helvetica", 10),
                                                  foreground=self.colors[i])
            self.label_player_max_time[i].grid(row=2,
                                               column=2 * (i + 1) - 1,
                                               columnspan=2)

            self.labels_inform[i] = Label(self.info,
                                          text='',
                                          font=("Helvetica", 10),
                                          foreground='black')
            self.labels_inform[i].grid(row=i + 3, column=0, columnspan=4)

            self.labels_player_name[i] = Label(self.info,
                                               text="Player%d:" % (i),
                                               font=("Helvetica", 12),
                                               foreground=self.colors[i])
            self.labels_player_name[i].grid(row=0, column=2 * i)

            self.option_menus_vars[i] = StringVar(self.root)
            self.option_menus_vars[i].set(self.interractivePlayerName)
            self.option_menus[i] = OptionMenu(self.info,
                                              self.option_menus_vars[i],
                                              *self.possiblePlayers)
            self.option_menus[i].grid(row=0, column=2 * i + 1)

    def draw_game_grid(self):
        '''
        Draw empty 8x8 grid on the left side of the window.
        '''
        self.grid = Canvas(self.root,
                           bg="white",
                           height=self.gridh,
                           width=self.gridw)
        self.grid.bind("<Button 1>", self.place_stone_click_handler)
        gridsize = self.boardSize
        offy = self.offy
        offx = self.offx
        w = self.gridw
        h = self.gridh
        spacing = self.gridspacing
        # line around
        self.grid.create_line(offx, offy, offx, h - offy, w - offx, h - offy,
                              w - offx, offy, offx, offx)

        for x in range(0, gridsize):
            for y in range(0, gridsize):
                arrayText = '[' + str(y) + ',' + str(x) + ']'
                self.grid.create_text(offx + (spacing * x) + spacing / 2,
                                      offy + (spacing * y) + spacing / 2,
                                      text=arrayText)
        # line rows
        for rowy in range(offy + spacing, h - offy, spacing):
            self.grid.create_line(offx, rowy, w - offx, rowy)

        # line columns
        for colx in range(offx + spacing, w - offx, spacing):
            self.grid.create_line(colx, offy, colx, h - offy)

        self.grid.pack(side="left")

    def sleep_time_change_handler(self, event):
        '''
        Called after scale value change, updates the wait time between moves.
        :param event: slider change event
        '''
        self.game.sleep_time_ms = self.scale_var.get()

    def play_button_click_handler(self):
        '''
        Button listener for Play/Pause/RePlay etc.
        On button click prints slider value and start game.
        '''

        # set the players from dropdown menu if game is stopped
        if self.game_state == GameState.STOPPED:
            print("game_state " + str(self.game_state))
            self.interactive_player_ids = []
            for i in range(2):
                print(self.option_menus_vars[i].get())
                if self.option_menus_vars[i].get(
                ) == self.interractivePlayerName:
                    self.interactive_player_ids.append(i)

                    if i == 0:
                        self.game.player1.name = self.interractivePlayerName
                    else:
                        self.game.player2.name = self.interractivePlayerName

                else:
                    if i == 0:
                        player_class = self.possiblePlayers[
                            self.option_menus_vars[i].get()]
                        self.game.player1 = player_class(
                            self.game.player1_color, self.game.player2_color)

                    else:
                        player_class = self.possiblePlayers[
                            self.option_menus_vars[i].get()]
                        self.game.player2 = player_class(
                            self.game.player2_color, self.game.player1_color)

                    self.game.clear_game()

            self.game.current_player = self.game.player1
            self.game.current_player_color = self.game.player1_color
            print('player1 ' + str(self.game.player1_color))
            print('player2 ' + str(self.game.player2_color))

        #play game or start game if interactive
        if len(self.interactive_player_ids) != 0:
            if self.game_state == GameState.STOPPED:
                print("revert this commented out section below")
                #if not self.board.can_play(self.game.current_player, self.game.current_player_color):
                #    self.game.clear_game()
                #    self.button['text'] = 'Play'
                #else:
                self.game_state = GameState.RUNNING
                self.button['text'] = 'RePlay'
                print('can play ', self.interactive_player_ids)
                inform_str = 'Player%d plays' % (
                    self.interactive_player_ids[0])
                self.inform(inform_str, 'green')
                if len(self.interactive_player_ids
                       ) == 1 and self.interactive_player_ids[0] == 1:
                    self.game.play_game(self.interactive_player_ids[0])

            else:
                self.game_state = GameState.STOPPED
                self.button['text'] = 'Play'
                self.game.clear_game()
                # self.game.play_game(self.interactivePlayerId)
        else:
            if self.game_state == GameState.STOPPED or self.game_state == GameState.PAUSED:
                print('start')
                print('player1 ' + str(self.game.player1_color))
                print('player2 ' + str(self.game.player2_color))
                self.button['text'] = 'Pause'
                self.game.sleepTimeMS = self.scale_var.get()
                if self.game_state == GameState.STOPPED:
                    self.game.clear_game()
                self.game.pause(False)
                self.game_state = GameState.RUNNING
                print('player1 ' + str(self.game.player1_color))
                print('player2 ' + str(self.game.player2_color))
                self.game.play_game()
                print('game exited')
                if self.board.can_play(self.game.current_player_color
                                       ) and not self.wrong_move:
                    print('set pause state')
                    self.button['text'] = 'Continue'
                    self.game_state = GameState.PAUSED
                else:
                    print('set stopped state')
                    self.button['text'] = 'RePlay'
                    self.game_state = GameState.STOPPED
                    # self.game.clear_game()

            elif self.game_state == GameState.RUNNING:
                print('pause')
                self.game_state = GameState.PAUSED
                self.game.pause(True)

    def print_score(self):
        '''
        Set number of stones for both players.
        '''
        stones = self.board.get_score()
        self.print_player_num_stones(0, stones[0])
        self.print_player_num_stones(1, stones[1])

    def print_num_stones(self, stones):
        '''
        Set number of stones for both players.
        :param stones: array of player number of stones
        '''
        self.print_player_num_stones(0, stones[0])
        self.print_player_num_stones(1, stones[1])

    def print_player_num_stones(self, playerID, stones):
        '''
        Set player number of stones.
        :param playerID: 0 for player 1, 1 for player 2
        :param maxTime: maximal time of player
        '''
        self.label_player_stones[playerID]['text'] = str(stones)
        self.root.update()

    def print_move_max_times(self, maxTimesMS):
        '''
        Print maximal times for both players to the gui.
        :param max_times_ms: array of max time needed for move.
        '''
        self.print_player_move_max_time(0, maxTimesMS[0])
        self.print_player_move_max_time(1, maxTimesMS[1])

    def print_player_move_max_time(self, playerID, maxTime):
        '''
        Set player maximal time.
        :param playerID: 0 for player 1, 1 for player 2
        :param maxTime: maximal time of player
        '''
        self.label_player_max_time[playerID]['text'] = '%.2f [ms]' % maxTime
        self.root.update()

    def print_board_state(self):
        '''
        Show the state of the board in gui.
        '''
        # self.board.print_board()
        for y in range(self.board.board_size):
            for x in range(self.board.board_size):
                if self.board.board[y][x] == -1:
                    self.clear_stone(x, y)
                else:
                    self.draw_stone(x, y, self.board.board[y][x])
        self.root.update()

    def place_stone_click_handler(self, event):
        '''
        For interactive player places stone to mouse click position. 
        :param event: mouse click event
        '''
        print("place_stone_click_handler")
        if self.game_state != GameState.STOPPED and len(
                self.interactive_player_ids
        ) >= 1 and self.game.current_player_color in self.interactive_player_ids:
            pos_move = [
                int((event.y - self.offy) / self.gridspacing),
                int((event.x - self.offx) / self.gridspacing)
            ]

            if self.board.is_correct_move(pos_move,
                                          self.game.current_player_color):

                next_player_id = self.game.play_move(pos_move)
                self.print_board_state()
                self.print_score()
                self.print_move_max_times(self.game.max_times_ms)
                inform_str = 'Player%d plays' % (
                    self.game.current_player_color)
                self.inform(inform_str, 'green')
                if len(self.interactive_player_ids) == 1:
                    self.game.play_game(self.interactive_player_ids[0])

                if next_player_id == -1:
                    self.game_state = GameState.STOPPED
                    self.button['text'] = 'RePlay'
                    self.game.print_final_info()
            else:
                print('incorrect move', pos_move)
                self.inform(
                    'incorrect move to %d %d' % (pos_move[0], pos_move[1]),
                    'red')

    def inform(self, text_strs, color_str):
        '''
        Show inform text in gui.
        :param text_strs: string or string array of size 2 that is shown in gui
        :param color_str: color of shown text_strs
        '''
        inform_str_all = ['', '']
        if not isinstance(text_strs, list):
            inform_str_all[0] = text_strs
        else:
            inform_str_all = text_strs
        # print(inform_str_all)
        for i in range(2):
            self.labels_inform[i]['text'] = inform_str_all[i]
            self.labels_inform[i]['foreground'] = color_str
        self.root.update()
Пример #58
0
class SudokuUI(Frame):
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0
        self.__initUI()

    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Clear answers",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)

    def __draw_grid(self):
        for i in xrange(10):
            color = "blue" if i % 3 == 0 else "gray"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_puzzle(self):
        self.canvas.delete("numbers")
        for i in xrange(9):
            for j in xrange(9):
                answer = self.game.puzzle[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    original = self.game.start_puzzle[i][j]
                    color = "black" if answer == original else "sea green"
                    self.canvas.create_text(x,
                                            y,
                                            text=answer,
                                            tags="numbers",
                                            fill=color)

    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")
        self.__draw_puzzle()

    def __cell_clicked(self, event):
        if self.game.game_over:
            return

        x, y = event.x, event.y
        if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
            self.canvas.focus_set()

            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            elif self.game.puzzle[row][col] == 0 or self.game.puzzle[row][
                    col] != self.game.start_puzzle[row][col]:
                self.row, self.col = row, col
        else:
            self.row, self.col = -1, -1

        self.__draw_cursor()

    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(x0,
                                         y0,
                                         x1,
                                         y1,
                                         outline="red",
                                         tags="cursor")

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234567890":
            self.game.puzzle[self.row][self.col] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
            if self.game.check_win():
                self.__draw_victory()

    def __draw_victory(self):
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0,
                                y0,
                                x1,
                                y1,
                                tags="victory",
                                fill="dark orange",
                                outline="orange")
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(x,
                                y,
                                text="You win!",
                                tags="winner",
                                fill="white",
                                font=("Arial", 32))