当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.grid方法代码示例

本文整理汇总了Python中tkinter.Canvas.grid方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.grid方法的具体用法?Python Canvas.grid怎么用?Python Canvas.grid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.Canvas的用法示例。


在下文中一共展示了Canvas.grid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
def main():
    '''runs the program'''
    square_width = 64
    num_cols = 7
    num_rows = 6
    canvas_width = (num_cols+1)*square_width
    canvas_height = (num_rows+1)*square_width

    window = Tk()
    window.configure(background='black')
    window.title("DynaBLASTER")
    window.resizable(0,0) #removes maximize option
    #window.iconbitmap('icon.ico')
    #window.tk.call('tk', 'scaling', 20.0)

    canvas = Canvas(window, width=canvas_width, highlightthickness=0,
                    height=canvas_height, background='#717171')
    canvas.grid(row=1,column=0, columnspan=5)

    graphics = Graphics(canvas, num_rows, num_cols, square_width, window)
    board = Board(canvas, square_width, num_rows, num_cols,
                  canvas_width, canvas_height)
    col=0
    row=0
    player1 = Player(canvas, board, square_width, graphics, col, row)
    col = graphics.cols - 3
    row = graphics.rows - 3
    player2 = Player(canvas, board, square_width, graphics, col, row)

    # Import settings from bindings file
    bindings_file = open('bindings.json')
    p1_bindings, p2_bindings, gen_bindings = json.load(bindings_file)

    window.bind(key_release_of(p1_bindings["Up"]), lambda event:player1.key_release('Up'))
    window.bind(key_release_of(p1_bindings["Down"]), lambda event:player1.key_release('Down'))
    window.bind(key_release_of(p1_bindings["Left"]), lambda event:player1.key_release('Left'))
    window.bind(key_release_of(p1_bindings["Right"]), lambda event:player1.key_release('Right'))
    window.bind(p1_bindings["Up"], lambda event:player1.key_press('Up'))
    window.bind(p1_bindings["Down"],lambda event:player1.key_press('Down'))
    window.bind(p1_bindings["Left"], lambda event:player1.key_press('Left'))
    window.bind(p1_bindings["Right"], lambda event:player1.key_press('Right'))
    window.bind(p1_bindings["Bomb"], player1.place_bomb)

    window.bind(key_release_of(p2_bindings["Up"]), lambda event:player2.key_release('Up'))
    window.bind(key_release_of(p2_bindings["Down"]), lambda event:player2.key_release('Down'))
    window.bind(key_release_of(p2_bindings["Left"]), lambda event:player2.key_release('Left'))
    window.bind(key_release_of(p2_bindings["Right"]), lambda event:player2.key_release('Right'))
    window.bind(p2_bindings["Up"], lambda event:player2.key_press('Up'))
    window.bind(p2_bindings["Down"], lambda event:player2.key_press('Down'))
    window.bind(p2_bindings["Left"], lambda event:player2.key_press('Left'))
    window.bind(p2_bindings["Right"], lambda event:player2.key_press('Right'))
    window.bind(p2_bindings["Bomb"], player2.place_bomb)

    window.bind(gen_bindings["Pause"], lambda event:pause_game(player1, player2, graphics))

    window.mainloop()
开发者ID:abel465,项目名称:DynaBLASTER,代码行数:58,代码来源:DynaBLASTER.py

示例2: initUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
    def initUI(self):
        self.parent.title("Mario's Picross Puzzle Editor")
        self.puzzles = None

        # Build the menu
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        self.fileMenu = fileMenu
        fileMenu.add_command(label="Open Mario's Picross ROM...",
                              command=self.onOpen)
        fileMenu.add_command(label="Save ROM as...",
                             command=self.onSave,
                             state=DISABLED)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        # Navigation
        Label(self.parent).grid(row=0, column=0)
        Label(self.parent).grid(row=0, column=4)
        self.parent.grid_columnconfigure(0, weight=1)
        self.parent.grid_columnconfigure(4, weight=1)

        prevButton = Button(self.parent,
                            text="<--",
                            command=self.onPrev,
                            state=DISABLED
        )
        self.prevButton = prevButton
        prevButton.grid(row=0, column=1)

        puzzle_number = 1
        self.puzzle_number = puzzle_number
        puzzleNumber = Label(self.parent, text="Puzzle #{}".format(puzzle_number))
        self.puzzleNumber = puzzleNumber
        puzzleNumber.grid(row=0, column=2)

        nextButton = Button(self.parent,
                            text="-->",
                            command=self.onNext,
                            state=DISABLED
        )
        self.nextButton = nextButton
        nextButton.grid(row=0, column=3)

        # Canvas
        canvas = Canvas(self.parent)
        self.canvas = canvas
        for i in range(15):
            for j in range(15):
                fillcolor = "gray80"
                self.canvas.create_rectangle(10+20*j,     10+20*i,
                                             10+20*(j+1), 10+20*(i+1),
                                             fill=fillcolor,
                                             tags="{},{}".format(i, j)
                )
        self.canvas.bind("<ButtonPress-1>", self.onClick)
        canvas.grid(row=1, columnspan=5, sticky=W+E+N+S)
        self.parent.grid_rowconfigure(1, weight=1)
开发者ID:sopoforic,项目名称:cgrr-mariospicross,代码行数:62,代码来源:marios_picross_puzzle_editor_gui.py

示例3: ListDialog

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
开发者ID:gokai,项目名称:tim,代码行数:60,代码来源:dialog.py

示例4: TkWindow

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class TkWindow(tkinter.Tk):
    def __init__(self,parent):
        tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        buttonFile = tkinter.Button(self,text=u"Get file",command=self.getFile)
        buttonFile.grid(column=0,row=1,sticky='EW',padx=10,pady=10)

        buttonCrypto = tkinter.Button(self,text=u"Crypto",command=self.crypto)
        buttonCrypto.grid(column=0,row=3,sticky='EW',padx=10,pady=10)

        #labelHeader = Tkinter.Label(self,text=u"Database file:",anchor="w")
        #labelHeader.grid(column=0,row=0,columnspan=3,padx=10,pady=10,sticky='EW')
        self.labelVariable = tkinter.StringVar()
        labelFileName = tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="black",bg="white")
        labelFileName.grid(column=1,row=1,columnspan=2,sticky='EW',padx=10,pady=10)

        self.canvas = Canvas(self,width=400, height=400,bd=0,bg="blue")
        self.canvas.grid(row = 2,column = 0,columnspan=2,sticky='EW',padx=10,pady=10)
        #self.photo = ImageTk.PhotoImage(file = "/home/paulina/obrazki/obrazek.jpg")
        #self.canvas.create_image(0,0, image = self.photo)


    def getFile(self):
        self.fileName = filedialog.askopenfilename(initialdir = "/home/paulina/obrazki",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        self.labelVariable.set(self.fileName)

        self.photo = Image.open(self.fileName)
        (imageSizeWidth, imageSizeHeight) = self.photo.size
        print(imageSizeWidth, imageSizeHeight)

        newImageSizeHeight = 400
        n = imageSizeHeight/newImageSizeHeight
        print(n)
        newImageSizeWidth = int(imageSizeWidth/n)
        print(newImageSizeWidth, newImageSizeHeight)

        self.canvas.config(width=newImageSizeWidth,height=newImageSizeHeight)
        self.photo = self.photo.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
        self.photo = ImageTk.PhotoImage(self.photo)
        self.canvas.create_image(int(newImageSizeWidth/2), int(newImageSizeHeight/2), image = self.photo)

    def crypto(self):
        obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
        message = "The answer is no"
        ciphertext = obj.encrypt(message)
        print(ciphertext)
        obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
        messagedec = obj2.decrypt(ciphertext)
        print(messagedec)
开发者ID:PaulinaWrobel,项目名称:CryptographicEmbeddedSystem,代码行数:56,代码来源:ClassCES_p.py

示例5: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
 def __init__(self):
   self.app = Tk()
   self.app.title('Connect4')
   self.app.resizable(width=False, height=False)
   self.board = Board()
   self.buttons = {}
   self.frame = Frame(self.app, borderwidth=1, relief="raised")
   self.tiles = {}
   for x in range(self.board.width):
     handler = lambda x=x: self.move(x)
     button = Button(self.app, command=handler, font=Font(family="Helvetica", size=14), text=x+1)
     button.grid(row=0, column=x, sticky="WE")
     self.buttons[x] = button
   self.frame.grid(row=1, column=0, columnspan=self.board.width)
   for x,y in self.board.fields:
     tile = Canvas(self.frame, width=60, height=50, bg="navy", highlightthickness=0)
     tile.grid(row=self.board.height-1-y, column=x)
     self.tiles[x,y] = tile
   handler = lambda: self.reset()
   self.restart = Button(self.app, command=handler, text='reset')
   self.restart.grid(row=2, column=0, columnspan=self.board.width, sticky="WE")
   self.update()
开发者ID:HouriaDanesh,项目名称:connectfour,代码行数:24,代码来源:connectfour2.py

示例6: initui

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
    def initui(self):

        self.parent.title("Light pollution map")
        self.style = Style()
        self.style.theme_use("alt")

        self.grid(row=0, column=0)

        padding = {'padx':'5', 'pady':'5'}
        big_heading_font = ("Arial", 14, 'bold')
        small_heading_font = ("Arial", 10, 'bold')

        # Create frames.
        # There are three frames for settings - preprocessing, convolve, and contour.
        # Each also has an image frame underneath it.
        # Layout is as follows:
        #
        #             --------------------------------------------------------------------------
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             |   import_body   |   process_body  |   contour_body  |   export_body    |
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             --------------------------------------------------------------------------

        # Settings frames

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        import_body = Frame(self, relief=RAISED, borderwidth=1)
        import_body.grid(row=0, column=0, sticky=N+S+E+W)

        process_body = Frame(self, relief=RAISED, borderwidth=1)
        process_body.grid(row=0, column=1, sticky=N+S+E+W)

        contour_body = Frame(self, relief=RAISED, borderwidth=1)
        contour_body.grid(row=0, column=2, sticky=N+S+E+W)

        export_body = Frame(self, relief=RAISED, borderwidth=1)
        export_body.grid(row=0, column=3, sticky=N+S+E+W)

         # =============================================================================================================
        #
        # Contents of load_image_frame
        #
        # =============================================================================================================

        # Heading

        processing_frame_header = Label(import_body, text="Import", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, sticky=N, **padding)

        filename_variable = StringVar()

        # Import image

        import_canvas = Canvas(import_body, width=canvas_size, height=canvas_size, background='black')
        import_canvas.grid(row=1, column=0, sticky=N, **padding)

        # Load file method

        def choosefile():
            filename_variable.set(filedialog.askopenfilename(parent=import_body))
            image = Image.open(filename_variable.get())
            thumbnail = create_thumbnail(image, canvas_size)
            import_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        load_image_button = Button(import_body, text="Import image", command=choosefile)
        load_image_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding)
        import_body.rowconfigure(2, weight=1)

        # =============================================================================================================
        #
        # Contents of processing_frame
        #
        # =============================================================================================================

        processing_frame_header = Label(process_body, text="Process", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, columnspan=2, sticky=N, **padding)

        clipping_variable = IntVar()

        constants_label = Label(process_body, text="Clipping",
                                font=("Arial", 10, 'bold'))
        constants_label.grid(row=1, column=0, sticky=E, **padding)

        clipping_label = Label(process_body, text="Remove pixels with \n brightness under")
        clipping_label.grid(row=2, column=0, sticky=E, **padding)

        clipping_entry = Entry(process_body, textvariable=clipping_variable, width=4)
        clipping_entry.grid(row=2, column=1, sticky=W, **padding)

        clipping_variable.set(value=default_clipping_value)
#.........这里部分代码省略.........
开发者ID:arran-dengate,项目名称:light-pollution,代码行数:103,代码来源:controller.py

示例7: BoardArea

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class BoardArea(Observer):
    '''
    Represent the area in which the player will play.
    
    @ivar _regions: Dictionary <game cell, screen rectangle>
    @ivar _selection: the current cell selected to move.
        If there's no selection, the value is None.
    '''
    
    def __init__(self, game, parent):
        '''Initialize the canvas, the observers and the mouse bindings.'''
        
        Observer.__init__(self)
        self._game = game
        self._game.add_observer(self, 'CELL_OFF')
        self._game.add_observer(self, 'CELL_ON')
        
        self._canvas = Canvas(parent, bg=BOARD_BG_COLOR, width=280, height=280)
        self._canvas.grid(row=0, columnspan=3)
        self._canvas.bind("<Button-1>", self.left_button_pressed)
        
        self._regions = {}
        self.__init_regions(self._game)
        self._selection = None
    
    
    def get_selection(self):
        '''Getter of _selection.'''
        
        return self._selection
    
    
    def set_selection(self, sel):
        '''Setter of _selection.'''
        
        self._selection = sel
    
    
    def __init_regions(self, game):
        '''Complete the _regions dictionary.'''
        
        canvas_x = 0
        canvas_y = 0
        for x_index in range(7):
            for y_index in range(7):
                if (x_index, y_index) in game.get_board():
                    self._regions[(x_index, y_index)] =         \
                        Rectangle((canvas_x, canvas_y),         \
                        (canvas_x + BOARD_RECTANGLE_SIZE - 1,   \
                        canvas_y + BOARD_RECTANGLE_SIZE - 1))
                canvas_x += BOARD_RECTANGLE_SIZE
            canvas_x = 0
            canvas_y += BOARD_RECTANGLE_SIZE
    
    
    def left_button_pressed(self, event):
        '''The mouse left button was pressed, so if there's no
        selection, it's created, and if the selection exists,
        attempt to make a movement taking the selection position
        and the current position.'''
        
        pos = self.get_position_from_pixels(event.x, event.y)
        if pos is not None:
            if self.get_selection() is None:
                self.set_selection(pos)
                self.make_selection(pos)
            else:
                self._game.move(self.get_selection(), pos)
                self.clear_selection(self.get_selection())
                self.set_selection(None)
    
    
    def make_selection(self, pos):
        '''A selection was made.'''
        
        self.__selection(pos, BOARD_SEL_COLOR)
    
    
    def clear_selection(self, pos):
        '''No longer selection in the position given.'''
        
        self.__selection(pos, BOARD_BG_COLOR)
    
    
    def __selection(self, pos, color):
        '''Draw the selection rectangle.'''
        
        self._regions[pos].display_on(self._canvas, outline=color)
    
    
    def update(self, aspect, value):
        '''The board organization in the model has changed.'''
        
        if aspect == 'CELL_ON':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_NOT_EMPTY_COLOR)
        elif aspect == 'CELL_OFF':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_EMPTY_COLOR)
    
#.........这里部分代码省略.........
开发者ID:ngarbezza,项目名称:pysenku,代码行数:103,代码来源:pysenku-0.2.py

示例8: Nim

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class Nim(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title("Nim")
        self.kamen = PhotoImage(file = './kamen.ppm')
        self.nacin = BooleanVar() #0 is ai, 1 is human
        self.nacin = 0
        self.zahtevnost = DoubleVar() #0, 1, 2 are (easy, medium hard)
        self.vnos_nacina = Entry(self, textvariable = "način")
        ni = Button(self, text="Nova igra", command=self.nova_igra)
        ni.grid(column = 2, row = 0)
        self.platno = Canvas(self, width=700, height = 500, bg='white')
        self.platno.grid(row= 3, column = 0, columnspan=4)
        self.vrhovi = []
        self.z1 = Radiobutton(self, text = "Skoraj Nepremagljivo!", variable = self.zahtevnost, value=1)
        self.z2 = Radiobutton(self, text = "Srednje zahtevno   ", variable = self.zahtevnost, value=2)
        self.z3 = Radiobutton(self, text = "Za majhne punčke ", variable = self.zahtevnost, value=3)
        self.z1.grid(column = 0, row = 0)
        self.z2.grid(column = 0, row = 1)
        self.z3.grid(column = 0, row = 2)
        self.z1.select()
        self.konec = Label()
        self.mainloop()

        
    def nova_igra(self):
#        print(self.zahtevnost.get())
        if self.vrhovi != []:
            self.unici_kamne()
            self.k1.destroy()
            self.k2.destroy()
            self.k3.destroy()
            self.ligralec.destroy()
#        print(self.vrhovi)
        self.vrhovi = [randint(1, 5), randint(1, 5), randint(1, 5)]
        self.kamni = [[],[],[]]
        self.narisi_kamne(1)
        self.ligralec = Label(self, text='Na vrsti ste vi!', bg='white', font=("Calibri",21))
        self.lracunalnik = Label(self, text='Na vrsti je računalnik', bg='white', font=("Calibri",21))
        self.k1 = Label(self, text="Prvi kupček", bg='white')
        self.k1.place(x = 10, y=220)
        self.k2 = Label(self, text="Drugi kupček", bg='white')
        self.k2.place(x = 10, y=330)
        self.k3 = Label(self, text="Tretji kupček", bg='white')
        self.k3.place(x = 10, y=440)
        self.ligralec.place(x=300, y=130)
        self.konec.destroy()

    def preveri_zmagovalca(self, igralec):
        if max(self.vrhovi)<1:
            self.ligralec.destroy()
            self.lracunalnik.destroy()
            if igralec == 0:
                self.konec = Label(text='Čestitamo, zmagali ste!', bg = 'white', font=("Calibri", 24))
            else:
                self.konec = Label(text = 'Več sreče prihodnjič!', bg = 'white', font=("Calibri",24))
            self.konec.place(x=150, y=250)
            self.k1.destroy()
            self.k2.destroy()
            self.k3.destroy()

    def sestevek(self):
        s = 0
        for i in range(len(self.vrhovi)):
            s = s^self.vrhovi[i]
        return s
    def sestevki(self):
        return [a^self.X < a for a in self.vrhovi]
    def naredi_potezo_AI(self):
        #Ta del kode sem dobil tako, da sem priredil kodo iz wikipedije
        #vir: http://en.wikipedia.org/wiki/Nim
        self.X = self.sestevek()
        S = self.sestevki()
        odstranjenih = 0
        if self.X == 0:
            if max(self.vrhovi) >1:
                print("Can't win")
            for i, vrh in enumerate(self.vrhovi):
                if vrh>0:
                    izbrani, odstranjenih = i, vrh
        else:
            izbrani = S.index(True)
            odstranjenih = self.vrhovi[izbrani] - (self.vrhovi[izbrani]^self.X)
            dva_alivec = 0
            for i, vrh in enumerate(self.vrhovi):
                if i == izbrani:
                    if vrh-odstranjenih > 1:
                        dva_alivec += 1
                else:
                    if vrh > 1:
                        dva_alivec += 1
            if dva_alivec == 0:
                izbrani = self.vrhovi.index(max(self.vrhovi))
                vrhov_z1 = sum(v == 1 for v in self.vrhovi)
                if vrhov_z1%2 == 1:
                    odstranjenih = self.vrhovi[izbrani]-1
                else:
                    odstranjenih = self.vrhovi[izbrani]
                    
        if odstranjenih == 0:
#.........这里部分代码省略.........
开发者ID:Januar1,项目名称:nim_game,代码行数:103,代码来源:nim.py

示例9: Radiobutton

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
Radiobutton(modeFrame, text=" SAP Classical Mode", variable=mode, value=2, command=modesel).grid(row=1,sticky=W+E+N+S,ipadx=10,ipady=10)



##Select Operation Frame.....
opsFrame = LabelFrame(window,text="Select Operation")
opsFrame.grid(row=0,column=2,ipadx=10,ipady=10) 
Radiobutton(opsFrame, text=" Backup using Snapshots ", variable=ops, value=1, command=operation).grid(row=0,sticky=W+E+N+S,ipadx=10,ipady=5)
Radiobutton(opsFrame, text=" Recover System ", variable=ops, value=2,command=operation).grid(row=1,sticky=W+E+N+S,ipadx=10,ipady=5)
Radiobutton(opsFrame, text=" System Copy using Snapshots ", variable=ops, value=3,command=operation).grid(row=2,sticky=W+E+N+S,ipadx=10,ipady=5)
print ( "Inside Operation New... ")


##Photo Image embed
canvas = Canvas(window)
canvas.grid(row = 0, column = 3)
photo = PhotoImage(file = 'ps_200.gif')
canvas.create_image(200,130,image=photo)

##Select SID Selection Frame.....
sidFrame = LabelFrame(window,text="Main")
sidFrame.grid(row=1,column=0) 

##Label(sidFrame, text=" Select Source SID...").grid(row=0,column=0,columnspan=10)
vSourceSID = StringVar(sidFrame)
vSourceSID.set("Source SID")
sidMenuSource = OptionMenu(sidFrame, vSourceSID, "Source SID","PSD","QSD","DSD")
sidMenuSource.grid(row=0,column=0)

##Label(sidFrame, text=".............").grid(row=0, column=0,columnspan=20,sticky=W)
开发者ID:krishnasatyavarapu,项目名称:SAP_HANA,代码行数:32,代码来源:PureFlashManager_githubVersion.py

示例10: GUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class GUI():

    """
    Method gets a Tk instance (master) and a model instance implemented with nengo.
    It then creates a GUI with the polts that where specified in create_plot(...).
    """

    def __init__(self, master, model):
        self.f = 0

        master.rowconfigure(0, weight=1)
        master.columnconfigure(0, weight=1)

        self.frame = tk.Frame(master)
        self.frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.frame.grid(sticky=NSEW)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)

        self.scroll_canvas = Canvas(self.frame)
        self.scroll_canvas.grid(row=0, column=0, sticky=NSEW)

        xScrollbar = Scrollbar(self.frame, orient=HORIZONTAL)
        yScrollbar = Scrollbar(self.frame)

        xScrollbar.grid(row=1, column=0, sticky=EW)
        yScrollbar.grid(row=0, column=1, sticky=NS)

        self.scroll_canvas.config(xscrollcommand=xScrollbar.set)
        xScrollbar.config(command=self.scroll_canvas.xview)
        self.scroll_canvas.config(yscrollcommand=yScrollbar.set)
        yScrollbar.config(command=self.scroll_canvas.yview)

        self.create_plot(model)

        self.figure_canvas = FigureCanvasTkAgg(self.f, master=self.scroll_canvas)
        self.canvas = self.figure_canvas.get_tk_widget()
        self.canvas.pack(side=tk.TOP, fill=tk.BOTH, padx=5, pady=5, expand=1)

        self.scroll_canvas.create_window(0, 0, window=self.canvas)
        self.scroll_canvas.config(scrollregion=self.scroll_canvas.bbox(ALL))
        self.figure_canvas.show()

        self.toolbar = NavigationToolbar2TkAgg(self.figure_canvas, self.scroll_canvas)
        self.toolbar.pack()
        self.toolbar.update()

        """
        Adds the specified plots to the figure displayed in the GUI. It gets a model instance implemented with nengo
        """
    def create_plot(self, model):

        self.f = Figure(figsize=(16, 9), dpi=80)

        """
        Example plot which plots the integrators back connection, its input, its real value and the real robot goal angle
        """
        self.ax00 = self.f.add_axes((.2, .2, .6, .6), axisbg=(.75, .75, .75), frameon=True)
        self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_probe], label = 'Integrator')
        self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_connection_probe], label = 'Con')
        self.ax00.plot(model.sim.trange(), model.sim.data[model.integrator_self_connection_probe], label = 'Self Con')
        self.ax00.plot(model.sim.trange(), model.sim.data[model.robot_goal_neuron_probe][:, 2], label = 'Real')
        self.ax00.legend()
开发者ID:juptrk,项目名称:RobotNavigationWithNengo,代码行数:66,代码来源:gui.py

示例11: Button

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
# label.pack(fill=BOTH)

top.pack()
advancedFrame.pack(anchor = "nw", pady = 20)

getBtn = Button(top, text = "打开", command = getfilepath, width = 10)
outBtn = Button(top, text = "输出目录", command = outfilepath, width = 10)
analyseBtn = Button(top, text = "开始", command = go, width = 10)

customNameLabel = Label(advancedFrame, text = "自定义名称 : ", width = 10)
customNameLabel.propagate(False)
customNameLabel.pack(anchor = "nw", side = "left")
outNameEntry.pack(anchor = "ne", side = "left")
cutlimitLabel = Label(advancedFrame, text = "大小限制 : ")
cutlimitLabel.pack(anchor = "nw", side = "left")
limitXEntry.pack(anchor = "ne", side = "left")
Label(advancedFrame, text="X", width = 2).pack(anchor = "ne", side = "left")
limitYEntry.pack(anchor = "nw", side = "left")

filePathLabel.grid(row = 0, column = 0)
getBtn.grid(row = 0, column = 1)
outDictoryLabel.grid(row = 1, column = 0)
outBtn.grid(row = 1, column = 1)
analyseBtn.grid(row = 3, column = 1)
bar.grid(row = 3, column = 0)

top.mainloop()

# if __name__ == "__main__":
# main()
开发者ID:LaoQi,项目名称:pngTexturePacker,代码行数:32,代码来源:main.py

示例12: Tk

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
# Config
#
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 800
RADIUS = 12 
PAD = 4

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

canvas = Canvas(root)
canvas['width'] = CANVAS_WIDTH
canvas['height'] = CANVAS_HEIGHT

canvas.grid(column=0, row=0, sticky=(N, W, E, S))

''' Draws a circle at (x, y, r)'''
def drawCircle(circle):
    global canvas
    x, y, r = circle[0], circle[1], circle[2]
    canvas.create_oval(x - r, y - r, x + r, y + r) 

''' 
Returns a point (x,y) on circle that's at an angle of theta degrees to the x-axis
'''
def pointOnCircle(theta, circle):
    theta = math.radians(theta)
    x, y, r = circle[0], circle[1], circle[2]
    return (r * math.cos(theta) + x, y - r * math.sin(theta))
开发者ID:spatel78745,项目名称:gserv2,代码行数:32,代码来源:gserv.py

示例13: BoardArea

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class BoardArea(Observer):
    '''
    Represent the area in which the player will play.
    
    @ivar _selection: the current cell selected to move.
        If there's no selection, the value is None.
    '''
    
    def __init__(self, game, parent):
        '''Initialize the canvas, the observers and the mouse bindings.'''
        Observer.__init__(self)
        self._game = game
        self._game.add_observer(self, 'CELL_OFF')
        self._game.add_observer(self, 'CELL_ON')
        self._canvas = Canvas(parent, width=280, height=280)
        self._canvas.config(bg=CONFIG['BOARD_BG_COLOR'])
        self._canvas.grid(row=0, columnspan=4)
        self._canvas.bind("<Button-1>", self.left_button_pressed)
        self._selection = None
    
    def get_selection(self):
        '''Getter of _selection.'''
        return self._selection
    
    def set_selection(self, sel):
        '''Setter of _selection.'''
        self._selection = sel
    
    def left_button_pressed(self, event):
        '''The mouse left button was pressed, so if there's no
        selection, it's created, and if the selection exists,
        attempt to make a movement taking the selection position
        and the current position.'''
        pos = self.get_position_from_pixels(event.x, event.y)
        if pos is not None:
            if self.get_selection() is None:
                self.set_selection(pos)
                self.make_selection(pos)
            else:
                move_command = Move(self._game, self.get_selection(), pos)
                move_command.execute()
                self.clear_selection(self.get_selection())
                self.set_selection(None)
    
    def make_selection(self, pos):
        '''A selection was made.'''
        self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_SEL_COLOR'])
    
    def clear_selection(self, pos):
        '''No longer selection in the position given.'''
        self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_BG_COLOR'])
    
    def draw_sel_rect_from_pos(self, pos, color):
        '''Draw the selection rectangle.'''
        rect_size = CONFIG['BOARD_RECT_SIZE']
        origin_x = pos[1] * rect_size
        origin_y = pos[0] * rect_size
        self._canvas.create_rectangle(origin_x, origin_y, \
            origin_x + rect_size, origin_y + rect_size, outline=color)
    
    def update(self, aspect, value):
        '''The board organisation in the model has changed.'''
        if aspect == 'CELL_ON':
            self.draw_circle_from_pos(value, CONFIG['CELL_COLOR'])
        elif aspect == 'CELL_OFF':
            self.draw_circle_from_pos(value, CONFIG['HOLE_COLOR'])
    
    def draw_circle_from_pos(self, pos, color):
        '''Draw a cell empty or not empty.'''
        rect_size = CONFIG['BOARD_RECT_SIZE']
        dist = CONFIG['DIST']
        origin_x = pos[1] * rect_size + dist
        origin_y = pos[0] * rect_size + dist
        corner_x = origin_x + rect_size - dist * 2
        corner_y = origin_y + rect_size - dist * 2
        self._canvas.create_oval(origin_x, origin_y, \
                                 corner_x, corner_y, fill=color)
    
    def get_position_from_pixels(self, x_coord, y_coord):
        '''Get the board position corresponding with the
        coordinates given.'''    
        pos_y = int(x_coord / CONFIG['BOARD_RECT_SIZE'])
        pos_x = int(y_coord / CONFIG['BOARD_RECT_SIZE'])
        if (pos_x, pos_y) in self._game.get_board():
            return (pos_x, pos_y)
        else:
            return None
开发者ID:ngarbezza,项目名称:pysenku,代码行数:89,代码来源:pysenku-0.5.py

示例14: RadiobuttonEntry

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class RadiobuttonEntry(ttk.Frame):
    """State entry for the entire conflict. A set of RadioButtonSeries."""

    def __init__(self, master, conflict):
        """State entry widget for the entire conflict."""
        ttk.Frame.__init__(self, master)

        self.conflict = conflict

        self.rbeCanvas = Canvas(self)
        self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
        self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
                                     command=self.rbeCanvas.yview)

        self.rbeCanvas.grid(column=0, row=0, columnspan=2, sticky=NSEW)
        self.scrollY.grid(column=2, row=0, sticky=NSEW)
        self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
        self.canvWindow = self.rbeCanvas.create_window((0, 0),
                                                       window=self.rdBtnFrame,
                                                       anchor='nw')

        self.rowconfigure(0, weight=1)

        self.entryText = StringVar(value='')

        vcmd = self.register(self.onValidate)
        self.entryBx = ttk.Entry(self, textvariable=self.entryText,
                                 validate="key",
                                 validatecommand=(vcmd, '%S', '%P'))
        self.entryBx.grid(column=0, row=1, sticky=NSEW)
        self.entryBx.bind('<Return>', self.generateAdd)

        self.warnText = StringVar(value='')
        self.warnLab = ttk.Label(self, textvariable=self.warnText, width=18)
        self.warnLab.grid(column=1, row=1, sticky=NSEW)

        self.codeText = StringVar(value='')

        vcmd2 = self.register(self.onValidate2)
        self.codeBx = ttk.Entry(self, textvariable=self.codeText,
                                validate="key",
                                validatecommand=(vcmd2, '%S', '%P'))
        self.codeBx.grid(column=0, row=2, sticky=NSEW)
        self.codeBx.bind('<Return>', self.generateAdd)

        self.warnText2 = StringVar(value='')
        self.warnLab2 = ttk.Label(self, textvariable=self.warnText2)
        self.warnLab2.grid(column=1, row=2, sticky=NSEW)

        self.addBtn = ttk.Button(self, text='Add as Prefered State',
                                 command=self.generateAdd)
        self.stageBtn = ttk.Button(self, text='Add to Staging',
                                   command=self.generateStage)

        self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
        self.stageBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)

        self.isDisabled = False

        self.columnconfigure(0, weight=1)

        self.reloadOpts()

        self.regexValidChars = re.compile(r'^[-\d, fi]*$')
        self.regexStatesIf = re.compile(r'^ *(-)?(\d+) *iff? *(-)?(\d+) *$')
        self.regexStates = re.compile(r' *(-)?(\d+) *')

        self.hasValidIf = False

    def resize(self, event=None):
        """Adjust the canvas widget if the window is resized."""
        self.rbeCanvas.configure(scrollregion=self.rbeCanvas.bbox("all"))
        self.rbeCanvas["width"] = self.rbeCanvas.bbox("all")[2]

    def generateAdd(self, event=None):
        """Generate event if a preference is added."""
        self.event_generate('<<AddPref>>')

    def generateStage(self, event=None):
        """Generate event if a preference is staged."""
        self.event_generate('<<StagePref>>')

    def reloadOpts(self):
        """Reload options for all decision makers."""
        self.rbeCanvas.delete(self.canvWindow)
        self.rdBtnFrame.destroy()
        self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
        self.canvWindow = self.rbeCanvas.create_window((0, 0),
                                                       window=self.rdBtnFrame,
                                                       anchor='nw')
        self.rdBtnFrame.bind('<<RdBtnChg>>', self.rdBtnChgCmd)
        self.rdBtnFrame.bind("<Configure>", self.resize)

        self.rdBtnSrs = []
        self.stringVarList = []

        for x, dm in enumerate(self.conflict.decisionMakers):
            a = RadiobuttonSeries(self.rdBtnFrame, dm)
            self.rdBtnSrs.append(a)
            a.setOpts(dm.options)
#.........这里部分代码省略.........
开发者ID:onp,项目名称:gmcr-py,代码行数:103,代码来源:widgets_f04_01_prefRadioButton.py

示例15: Board

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import grid [as 别名]
class Board(Tk):
    def __init__(self, width, height, cellSize,player=None,logicBoard=None):
        """

        :param width: largeur du plateau
        :param height: hauteur du plateau
        :param cellSize: largeur des cases
        :param player: joueur
        :param logicBoard: plateau logique (liste de liste)
        """
        Tk.__init__(self)
        self.cellSize = cellSize
        self.guiBoard = Canvas(self, width=width, height=height, bg="bisque")
        self.currentFixedLabel = FixedLabel(self,"CURRENT PLAYER : ",16,0)
        self.currentVariableLabel = VariableLabel(self,18,0,"string")
        self.bluePointsFixedLabel = FixedLabel(self,"BLUE CAPTURES : ",16,2)
        self.bluePointsVariableLabel = VariableLabel(self,18,2,"integer")
        self.redPointsFixedLabel = FixedLabel(self,"RED CAPTURES : ",16,4)
        self.redPointsVariableLabel = VariableLabel(self,18,4,"integer")
        self.logicBoard=logicBoard
        if not(logicBoard):
            self.logicBoard=dr.initBoard(DIMENSION)
        self.player=player
        if not(player):
            self.player=1
        self.hasPlayed=False
        self.hasCaptured=False
        self.guiBoard.bind("<Button -1>", self.bindEvent)
        self.initiateBoard()
        self.guiBoard.grid(rowspan=DIMENSION+1,columnspan=DIMENSION+1,row=0,column=4)

    def getBoard(self):
        return(self.logicBoard)

    def getPlayer(self):
        return(self.player)

    def initiateBoard(self):

        for i in range(DIMENSION):
            for j in range(DIMENSION):
                coordX1 = (i * self.cellSize)
                coordY1 = (j * self.cellSize)
                coordX2 = coordX1 + self.cellSize
                coordY2 = coordY1 + self.cellSize
                color = "white" if i%2 == j%2 else "black"
                cell = self.logicBoard[j][i]
                guiCell=self.draw_rectangle(coordX1, coordY1, coordX2, coordY2, color, "r"+str(i)+str(j))
                if cell !=0:
                    pawnColor = "red" if cell > 0 else "blue"
                    pawn=self.draw_circle(coordX1, coordY1, coordX2, coordY2, pawnColor, "c"+str(i)+str(j),pawnColor)

    def draw_rectangle(self,coordX1,coordY1,coordX2,coordY2,color,tags):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :return: Id du rectangle
        """
        self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags)
        return(self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags))
    def draw_circle(self, coordX1, coordY1, coordX2,coordY2, color, tags,outline):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :param outline: couleur du bord du cercle
        :return: Id du cercle
        """
        return(self.guiBoard.create_oval(coordX1,coordY1,coordX2,coordY2,fill=color,outline=outline,tags=tags))

    def findLength(self,i,j,ancientSelectedCellTags):

        """

        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonne
        :param ancientSelectedCellTags: tags de la case anciennement selectionnée
        :return: longueur
        """
        departJ=int(ancientSelectedCellTags[0][1])
        departI=int(ancientSelectedCellTags[0][2])
        length=None
        if(departI!=i):
            isDiago=abs(j-departJ)/abs(i-departI)

            if(isDiago==1):#la case d'arrivée se trouve sur la diagonale
                length=( ((j-departJ)**2) + ((i-departI)**2) )**(1/2) #recherche de l'hypothenuse
                length/=(2)**(1/2) #divisé par racine de 2 car l'hypothenuse d'un triangle avec 2 coté de longueur 1 = racine de 2
        return(length)

    def findDirection(self,i,j,ancientSelectedCellTags):
#.........这里部分代码省略.........
开发者ID:malikfassi,项目名称:draughts,代码行数:103,代码来源:draughtsGUI.py


注:本文中的tkinter.Canvas.grid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。