コード例 #1
0
class mgcombocheckboxes:
    def __init__(self, topwin, itemkeyval):
        self.parentframe = topwin
        self.mb = Menubutton(topwin, text="CheckComboBox", relief=RAISED)
        self.mb.grid()
        self.mb.menu = Menu(self.mb, tearoff=0)
        self.mb["menu"] = self.mb.menu
        #
        #self.mb.menu["menu"] = self.mb.menu
        self.itemischecked = {}
        self.comboitemcount = 0
        for menuentry in itemkeyval:
            itemvar = IntVar()
            itemvar.set(itemkeyval[menuentry])
            # a keyvalue pair with menu item name and an itemvar unique to that selection
            self.itemischecked[menuentry] = itemvar
            self.mb.menu.add_checkbutton(label=menuentry, variable=itemvar)
            self.comboitemcount += 1
        #self.mb.config(menu=self.mb.menu)

    def grid(self, row, column):
        #self.mb.grid(row=5, column=7)
        pass

    #return the KV pairs of the combobuttons true/false checked or not
    def mgcombochecks_get(self):
        return self.itemischecked

    def mgcombochecks_add(self, itemstr):
        itemvar = IntVar()
        itemvar.set(False)
        # a keyvalue pair with menu item name and an itemvar unique to that selection
        self.itemischecked[itemstr] = itemvar
        self.mb.menu.add_checkbutton(label=itemstr, variable=itemvar)
        self.comboitemcount += 1
コード例 #2
0
 def menuHelp(self):
     "Set menu with help information"
     hbutton = Menubutton(self.bar, text='Help', underline=0)
     hbutton.grid(row=0, column=2, sticky='w')
     menu = Menu(hbutton, tearoff=0)
     menu.add_command(label='Keys (F1)',
                      command=lambda: msg.showinfo("Keys", KEYS))
     menu.add_command(label='About',
                      command=lambda: msg.showinfo("About", ABOUT))
     hbutton.configure(menu=menu)
コード例 #3
0
    def create_pull_down_menu(self):
        mb = Menubutton(self.master, text='Select API.', relief=RAISED)
        mb.grid()
        mb.menu = Menu(mb, tearoff=0)
        mb['menu'] = mb.menu
        var1 = IntVar()
        var2 = IntVar()
        var3 = IntVar()

        mb.menu.add_checkbutton(label="")
        return
コード例 #4
0
 def menuTag(self):
     "Set menu for working with tags"
     fbutton = Menubutton(self.bar, text='Tags', underline=0)
     fbutton.grid(row=0, column=1, sticky='w')
     menu = Menu(fbutton, tearoff=0)
     menu.add_command(label='Search... (/)',
                      command=lambda: self.openSearch(1))
     menu.add_command(label='Edit ([)',
                      command=lambda: self.panel[self.src].tagEdit(1))
     menu.add_command(label="Don't save (Esc)",
                      command=lambda: self.panel[self.src].tagExit(1))
     menu.add_command(label='Correct DB',
                      command=lambda: self.fo.correctDb())
     fbutton.configure(menu=menu)
コード例 #5
0
 def menuFile(self):
     "Set menu for file commands"
     cbutton = Menubutton(self.bar, text='Files', underline=0)
     cbutton.grid(row=0, column=0, sticky='w')
     menu = Menu(cbutton, tearoff=0)
     menu.add_command(label='Rename (F2)',
                      command=lambda: self.panel[self.src].rename(1))
     menu.add_command(label='Copy (F5)', command=lambda: self.copy(1))
     menu.add_command(label='Move (F6)', command=lambda: self.move(1))
     menu.add_command(label='New folder (F7)',
                      command=lambda: self.panel[self.src].newDir(1))
     menu.add_command(label='Equal panels (=)',
                      command=lambda: self.makeEqual(1))
     menu.add_separator({})
     menu.add_command(label='Quit (Ctrl+Q)',
                      command=lambda: self.root.destroy())
     cbutton.configure(menu=menu)
コード例 #6
0
def ventanaPrincipal():
    root=Tk()
    w= Frame(root)
    w.pack()
    
    bottomframe= Frame(root)
    bottomframe.pack(side=BOTTOM)
    
    mb1=Menubutton(bottomframe, text="Datos", relief=RAISED )
    mb1.menu =Menu(mb1, tearoff = 0 )
    mb1["menu"]=mb1.menu

    mb1.menu.add_command(label="Almacenar",command=fe.almacenarBD)
    mb1.menu.add_command(label="Listar",command=fp.list_bd)
    mb1.menu.add_command(label="Salir",command=root.destroy)

    mb1.grid(row=0,column=0)
    
    mb1=Menubutton(bottomframe, text="Buscar", relief=RAISED )
    mb1.menu =Menu(mb1, tearoff = 0 )
    mb1["menu"]=mb1.menu

    mb1.menu.add_command(label="Tema",command=fp.buscar_BD_Titulo)
    mb1.menu.add_command(label="Autor",command=fp.buscar_BD_Autor)
    mb1.menu.add_command(label="Fecha",command=fp.buscar_BD_Fecha)
   

    mb1.grid(row=0,column=1)
    
    
    mb1=Menubutton(bottomframe, text="Estadisticas", relief=RAISED )
    mb1.menu =Menu(mb1, tearoff = 0 )
    mb1["menu"]=mb1.menu

    mb1.menu.add_command(label="Temas mas populares",command=fp.popularesBD)
    mb1.menu.add_command(label="Temas mas activos",command=fp.activosBD)
   

    mb1.grid(row=0,column=2)
    
    #DESC
    
    root.mainloop()
コード例 #7
0
ファイル: gui.py プロジェクト: gcoinman/eth-wallet
    def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)

        self.configuration = Configuration().load_configuration()
        self.api = WalletAPI()
        self.tokens = self.api.list_tokens(self.configuration)
        self.eth_balance, _ = self.api.get_balance(self.configuration)

        def change_token(token):
            if token == 'ETH':
                self.eth_balance, _ = self.api.get_balance(self.configuration)
            else:
                self.eth_balance, _ = self.api.get_balance(self.configuration, token)

            balance.set(str(self.eth_balance) + ' ' + token)

        token_symbol = StringVar()
        token_symbol.set('ETH')
        balance = StringVar()
        balance.set(str(self.eth_balance) + ' ' + token_symbol.get())

        mb = Menubutton(self,
                        width=60,
                        textvariable=token_symbol,
                        relief=RAISED)
        mb.grid()
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_radiobutton(label="ETH",
                                variable=token_symbol,
                                value='ETH',
                                command=lambda: change_token(token_symbol.get()))
        for token in self.tokens:
            mb.menu.add_radiobutton(label=token,
                                    variable=token_symbol,
                                    value=token,
                                    command=lambda: change_token(token_symbol.get()))
        mb.pack()

        label = Label(self,
                      textvariable=balance,
                      width=60,
                      font=(None, 30))
        label.pack()

        lbl_address = Label(self,
                            text="To address:",
                            width=60,
                            font=(None, 20))
        lbl_address.pack()

        entry_address = Entry(self,
                              font=(None, 20),
                              width=60,
                              justify=CENTER)
        entry_address.pack()

        lbl_amount = Label(self,
                           text="Amount:",
                           width=60,
                           font=(None, 20))
        lbl_amount.pack()

        entry_amount = Entry(self,
                             font=(None, 20),
                             width=60,
                             justify=CENTER)
        entry_amount.pack()

        lbl_passphrase = Label(self,
                               text="Passphrase:",
                               width=60,
                               font=(None, 20))
        lbl_passphrase.pack()

        entry_passphrase = Entry(self,
                                 font=(None, 20),
                                 width=60,
                                 justify=CENTER)
        entry_passphrase.pack()

        btn_send = Button(self,
                          text="Send",
                          width=60,
                          font=(None, 16),
                          command=lambda: self.send_transaction(entry_address.get(),
                                                                entry_amount.get(),
                                                                entry_passphrase.get(),
                                                                token_symbol.get()))
        btn_send.pack()

        btn_back = Button(self,
                          text="Back",
                          width=60,
                          font=(None, 16),
                          command=self.navigate_home_page)
        btn_back.pack()
コード例 #8
0
ファイル: gui.py プロジェクト: gcoinman/eth-wallet
    def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)

        self.configuration = Configuration().load_configuration()
        self.api = WalletAPI()
        self.tokens = self.api.list_tokens(self.configuration)
        self.eth_balance, self.address = self.api.get_balance(self.configuration)

        def refresh():
            change_token(token_symbol.get())

        def change_token(token):
            if token == 'ETH':
                self.eth_balance, self.address = self.api.get_balance(self.configuration)
            else:
                self.eth_balance, self.address = self.api.get_balance(self.configuration, token)
            balance.set(str(self.eth_balance) + ' ' + token)

        token_symbol = StringVar()
        token_symbol.set('ETH')
        balance = StringVar()
        balance.set(str(self.eth_balance) + ' ' + token_symbol.get())

        mb = Menubutton(self,
                        width=60,
                        textvariable=token_symbol,
                        relief=RAISED)
        mb.grid()
        mb.menu = Menu(mb, tearoff=0)
        mb["menu"] = mb.menu
        mb.menu.add_radiobutton(label="ETH",
                                variable=token_symbol,
                                value='ETH',
                                command=lambda: change_token(token_symbol.get()))
        for token in self.tokens:
            mb.menu.add_radiobutton(label=token,
                                    variable=token_symbol,
                                    value=token,
                                    command=lambda: change_token(token_symbol.get()))
        mb.menu.add_radiobutton(label="Add new token ...",
                                command=self.navigate_add_token_page)
        mb.pack()

        label_address_lbl = Label(self,
                                  text='Address:',
                                  width=60,
                                  font=(None, 10, "bold"))
        label_address_lbl.pack()
        label_address = Label(self,
                              text=self.address,
                              width=60,
                              font=(None, 10))
        label_address.pack()

        label_balance = Label(self,
                              textvariable=balance,
                              width=60,
                              font=(None, 30))
        label_balance.pack()

        btn_refresh = Button(self,
                             text="Refresh",
                             command=refresh,
                             width=60,
                             font=(None, 16))
        btn_refresh.pack()

        btn_copy_address = Button(self,
                                  text="Copy address",
                                  command=self.copy_address,
                                  width=60,
                                  font=(None, 16))
        btn_copy_address.pack()

        btn_send_transaction = Button(self,
                                      text="Send Transaction",
                                      command=self.navigate_transaction_page,
                                      width=60,
                                      font=(None, 16))
        btn_send_transaction.pack()
コード例 #9
0
def RoomAvailibity():
    currentDate = datetime.datetime.now()
    currentDay = date.today()  #current date for schedule
    nextDay1 = date.today() + datetime.timedelta(days=1)
    nextDay2 = date.today() + datetime.timedelta(days=2)
    nextDay3 = date.today() + datetime.timedelta(days=3)
    nextDay4 = date.today() + datetime.timedelta(days=4)
    nextDay5 = date.today() + datetime.timedelta(days=5)
    nextDay6 = date.today() + datetime.timedelta(days=6)
    nextDay7 = date.today() + datetime.timedelta(days=7)

    year = currentDate.year
    day = currentDate.day
    month = currentDate.month

    # root=Tk()
    # root.title("Key")
    # root.geometry("200x200+1000+100")
    c2window = Tk()
    c2window.title("Available rooms")
    c2window.geometry("1000x600+10+100")
    conn = sqlite3.connect('hotel.db')
    cur = conn.cursor()
    sql = ' SELECT * FROM Room'
    cur.execute(sql)
    getAll = cur.fetchall()
    print(getAll[0])

    def checkIn(h):
        c2window.destroy()
        room(h)

    a = 99

    for row in range(22):

        for column in range(9):

            if row == 0:  #day of the week
                lable0 = Label(c2window,
                               text="Room Number",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable0.grid(row=0, column=0, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=currentDay.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=1, sticky="nsew", padx=1, pady=1)
                lable4 = Label(c2window,
                               text=nextDay1.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable4.grid(row=0, column=2, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay2.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=3, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay3.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=4, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay4.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=5, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay5.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=6, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay6.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=7, sticky="nsew", padx=1, pady=1)
                lable3 = Label(c2window,
                               text=nextDay7.strftime('%A'),
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=0, column=8, sticky="nsew", padx=1, pady=1)
            elif row == 1:  #date
                lable2 = Label(c2window,
                               text=str(currentDay.month) + "/" +
                               str(currentDay.day))
                lable2.grid(row=1, column=1, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay1.month) + "/" +
                               str(nextDay1.day))
                lable2.grid(row=1, column=2, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay2.month) + "/" +
                               str(nextDay2.day))
                lable2.grid(row=1, column=3, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay3.month) + "/" +
                               str(nextDay3.day))
                lable2.grid(row=1, column=4, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay4.month) + "/" +
                               str(nextDay4.day))
                lable2.grid(row=1, column=5, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay5.month) + "/" +
                               str(nextDay5.day))
                lable2.grid(row=1, column=6, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay6.month) + "/" +
                               str(nextDay6.day))
                lable2.grid(row=1, column=7, sticky="nsew", padx=1, pady=1)
                lable2 = Label(c2window,
                               text=str(nextDay7.month) + "/" +
                               str(nextDay7.day))
                lable2.grid(row=1, column=8, sticky="nsew", padx=1, pady=1)

            elif column == 0:
                a += 1
                label = Label(c2window, text=a)
                label.grid(row=row,
                           column=column,
                           sticky="nsew",
                           padx=1,
                           pady=1)
            else:

                label6 = Menubutton(c2window, text="Available")
                label6.grid(row=row,
                            column=column,
                            sticky="nsew",
                            padx=1,
                            pady=1)
                c2window.grid_columnconfigure(column, weight=1, uniform=1)
                label6.menu = Menu(label6)
                label6["menu"] = label6.menu
                if column == 1:
                    label6.menu.add_command(
                        label="check In",
                        command=lambda roomNumber=a: checkIn(roomNumber))
                else:
                    label6.menu.add_command(
                        label="Reservation",
                        command=lambda roomNumber=a: reservationSystem())
                # lambda  h = h ,row= row, column=column, l= label : availableRoom(row,column,h,l))
                # label.menu.add_command (label = "Reservation", command=lambda  h= h, row= row, column=column, l= label : occupiedRoom(row,column,h,l))

    def loadCheckin():
        conn = sqlite3.connect('hotel.db')
        cur = conn.cursor()
        sql = ' SELECT * FROM Room WHERE CheckIN =  ' + str(1)
        cur.execute(sql)
        result = cur.fetchall()

        def loadrooms(row, column, first_name):
            widget = c2window.grid_slaves(row=row, column=column)[0]
            widget.configure(bg="blue", fg="white", text=first_name)

        for row in result:
            if row[2] == 'Unavailable/Occupied':
                cur = conn.cursor()
                # sql = 'SELECT first_name, last_name FROM guests WHERE guest_id=' + str(row[6])
                # sql= 'SELECT CheckInDate , CheckOutDate from Room UNION ALL SELECT  first_name, last_name from guests WHERE guest_id=' +str(row[6])
                sql = 'SELECT RoomNumber,first_name, last_name, CheckInDate, CheckOutDate from guests INNER JOIN Room on Room.guestID = guests.guest_id'
                cur.execute(sql)
                guest = cur.fetchall()

        for row in guest:
            print(row)
            year1, month1, day1 = map(int, row[4].split('/'))
            d = date(year1, month1, day1)
            year, month, day = map(int, row[3].split('/'))
            c = date(year, month, day)
            days = (d - c).days
            cur = conn.cursor()
            # sql = 'SELECT first_name, last_name FROM guests WHERE guest_id=' + str(row[6])
            # sql= 'SELECT CheckInDate , CheckOutDate from Room UNION ALL SELECT  first_name, last_name from guests WHERE guest_id=' +str(row[6])
            sql = 'SELECT RowX, ColumnY FROM RoomAvailability WHERE RoomNumber =' + row[
                0]
            cur.execute(sql)
            roomHere = cur.fetchall()
            print(days)
            if days == 0:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
            elif days == 1:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])

            elif days == 2:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
            elif days == 3:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 3, row[1])
            elif days == 4:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 3, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 4, row[1])
            elif days == 5:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 3, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 4, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 5, row[1])
            elif days == 6:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 3, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 4, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 5, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 6, row[1])
            elif days == 7:
                loadrooms(roomHere[0][0], roomHere[0][1], row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 1, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 2, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 3, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 4, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 5, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 6, row[1])
                loadrooms(roomHere[0][0], roomHere[0][1] + 7, row[1])

    loadCheckin()
コード例 #10
0
ファイル: gui.py プロジェクト: LordSl/trpg_helper
    def run(self):
        self.realRoot = Tk()
        self.realRoot.attributes('-alpha', 0.75)
        self.realRoot.title('TRPGHelper')

        self.realRoot.protocol("WM_DELETE_WINDOW", lambda: os._exit(0))

        width = 260
        height = 400
        img = ImageTk.PhotoImage(
            Image.open('img/bg.png').resize((width, height)))
        l = Label(self.realRoot, image=img)
        l.grid(row=0, column=0)

        self.root = Frame(self.realRoot)
        self.root.grid(row=0, column=0)

        self.loadImg()
        self.entryFrame = Frame(self.root, height=50, width=120)
        self.rootFrame = Frame(self.root, height=100, width=120)

        self.entryFrame.grid(column=0)
        self.rootFrame.grid(row=2, column=0, sticky=W)

        ButtonRoomName = Button(self.entryFrame, height=1, text='房间')
        ButtonUserName = Button(self.entryFrame, height=1, text='用户')
        EntryRoomName = Entry(self.entryFrame, width=10)
        EntryUserName = Entry(self.entryFrame, width=10)

        MenuButtonState = Menubutton(self.entryFrame, text='选择状态', width=10)
        ms = Menu(MenuButtonState, tearoff=False)
        ms.add_command(label='我在线哦',
                       command=lambda: self.change_state(['-1', '3']))
        ms.add_command(label='真的很忙',
                       command=lambda: self.change_state(['-1', '4']))
        ms.add_command(label='等等我!',
                       command=lambda: self.change_state(['-1', '5']))
        ms.add_command(label='搞快点!',
                       command=lambda: self.change_state(['-1', '6']))
        ms.add_command(label='令人困惑',
                       command=lambda: self.change_state(['-1', '7']))
        ms.add_command(label='瓦特法?',
                       command=lambda: self.change_state(['-1', '8']))
        ms.add_command(label='懂了悟了',
                       command=lambda: self.change_state(['-1', '9']))
        MenuButtonState.configure(menu=ms)

        def _call_roomNameButton(roomName):
            self.data_role['roomName'] = roomName

        def _call_userNameButton_right():
            myHttpRequest(url_delUser,
                          {'userName': self.data_role['userName']})

        def _call_userNameButton_left(userName):
            if (userName != self.data_role['userName']):
                self.change_state(['1', '4'])
            self.data_role['userName'] = userName
            try:
                if (self.data_role['userName'] != '\0'):
                    myHttpRequest(url_register,
                                  {'userName': self.data_role['userName']})
                    myHttpRequest(
                        url_createRoom, {
                            'userName': self.data_role['userName'],
                            'roomName': self.data_role['roomName']
                        })
                    self.rebuild()
            except:
                print('userNameButton error')

        ButtonRoomName.bind(
            "<Button-1>", lambda f: _call_roomNameButton(EntryRoomName.get()))
        ButtonUserName.bind(
            "<Button-1>",
            lambda f: _call_userNameButton_left(EntryUserName.get()))
        ButtonUserName.bind("<Button-3>",
                            lambda f: _call_userNameButton_right())

        ButtonRoomName.grid(column=0, row=0, ipady=2, pady=5, ipadx=2, padx=5)
        ButtonUserName.grid(column=0, row=1, ipady=2, pady=5, ipadx=2, padx=5)
        EntryRoomName.grid(column=1, row=0, pady=5, ipadx=2, padx=5)
        EntryUserName.grid(column=1, row=1, pady=5, ipadx=2, padx=5)
        MenuButtonState.grid(column=2, row=0, pady=5, ipadx=2, padx=5)

        self.root.after(1000, self.update)
        self.root.mainloop()
コード例 #11
0
root = Tk()
root.title("My Text Editor")
root.resizable(False, False)

# The editor
text = Text(root)
text.grid()

# save button
button = Button(root, text="Save", command=save_as)
button.grid()

# hardcoded font button

fontSelection = Menubutton(root, text="Font", relief=RAISED)
fontMenu = Menu(fontSelection, tearoff=0)
helvetica = IntVar('Helvetica')
courier = IntVar('Courier')
fontMenu.add_checkbutton(label="Helvetica",
                         variable=helvetica,
                         command=font_helvetica)
fontMenu.add_checkbutton(label="Courier",
                         variable=courier,
                         command=font_courier)

fontSelection["menu"] = fontMenu
fontSelection.grid()

root.mainloop()
コード例 #12
0
ファイル: Notepad.py プロジェクト: nootz1999/Project_Learning
def boldDoc():
    global textarea
    textarea.config(font=('arial', 14, 'bold'))


root = Tk()
root.title("MicroService")
savebtn = Button(
    root,
    command=saveDoc,
    text="Save",
)
savebtn.grid(row=1, column=0)
savebtn.config(font=('cursive', 16, 'bold'), bg="Hotpink", fg="white")
fontbtn = Menubutton(root, text="Font")
fontbtn.config(font=('arial', 16, 'bold'), bg="#00FFFF", fg="white")
fontbtn.grid(row=1, column=1)
fontbtn.menu = Menu(fontbtn, tearoff=0)
fontbtn["menu"] = fontbtn.menu
fontbtn.menu.add_checkbutton(label="Arial", command=Arial)
fontbtn.menu.add_checkbutton(label="Algerian", command=Algerian)
fontbtn.menu.add_checkbutton(label="Cambria", command=Cambria)
fontbtn.menu.add_checkbutton(label="Courier", command=Courier)
boldbtn = Button(root, command=boldDoc, text="Bold")
boldbtn.grid(row=1, column=2)
boldbtn.config(font=('arial', 16, 'bold'), bg="#8B0000", fg="white")
textarea = Text(root)
textarea.grid(row=2, columnspan=5)

root.mainloop()
コード例 #13
0
def roomType():
    roomroot = Tk()
    roomroot.title("Key")
    roomroot.geometry("410x150+850+50")
    roomwindow = Toplevel()
    roomwindow.title("Room Type")
    roomwindow.geometry("800x200+0+50")
    h = 99  #set room to start at 99 then add 1 to make 100 initial starting room

    def closeWindow(roomNumber, l):
        roomwindow.destroy()
        room(roomNumber, l)
        roomroot.destroy()

    def makeAvailable(roomNumber):
        conn = sqlite3.connect('hotel.db')
        cur = conn.cursor()
        sql = 'UPDATE Room SET RoomStatus = "Available",CHeckIN = ' + str(
            0) + ', GuestID = ' + str('null') + ' WHERE roomNumber = ' + str(
                roomNumber)

        cur.execute(sql)
        conn.commit()

    def makeUnavailable(roomNumber):
        conn = sqlite3.connect('hotel.db')
        cur = conn.cursor()
        sql = 'UPDATE Room SET RoomStatus = "Unavailable/Occupied" WHERE roomNumber = ' + str(
            roomNumber)
        cur.execute(sql)
        conn.commit()

    def makeRoomDirty(roomNumber):
        conn = sqlite3.connect('hotel.db')
        cur = conn.cursor()
        sql = 'UPDATE Room SET RoomStatus = "Unavailable/Dirty" WHERE roomNumber = ' + str(
            roomNumber)
        cur.execute(sql)
        conn.commit()

    def makeRoomMaintance(roomNumber):
        conn = sqlite3.connect('hotel.db')
        cur = conn.cursor()
        sql = 'UPDATE Room SET RoomStatus = "Unavailable/Maintenance" WHERE roomNumber = ' + str(
            roomNumber)
        cur.execute(sql)
        conn.commit()

    #function to change color depends on status of the room
    def loadDirtyRoom(row, column):
        widget = roomwindow.grid_slaves(row=row, column=column)[0]
        widget.configure(bg="pink", fg="black")

    def loadOccupiedRoom(row, column):
        widget = roomwindow.grid_slaves(row=row, column=column)[0]
        widget.configure(bg="blue", fg="black")

    def loadMaintenanceRoom(row, column):
        widget = roomwindow.grid_slaves(row=row, column=column)[0]
        widget.configure(bg="red", fg="white")

    def loadAvailableRoom(row, column):
        widget = roomwindow.grid_slaves(row=row, column=column)[0]
        widget.configure(bg="green")

    def availableRoom(row, column, h, l):
        # print(label.grid_info())
        makeAvailable(h)
        # widget= window.grid_slaves(row=row, column=column)[0]
        # widget.configure(bg="green")
        l.configure(bg="green")

    def dirtyRoom(row, column, h, l):
        #print(label.grid_info())
        # makeRoomDirty(h)
        # loadDirtyRoom(row,column)
        # # widget= window.grid_slaves(row=row, column=column)[0]
        # # widget.configure(bg="pink",fg="black")
        # l.configure(bg="pink",fg="black")
        conn = sqlite3.connect('hotel.db')
        sql5 = 'SELECT * FROM Room WHERE RoomNumber=' + str(h)
        cur = conn.cursor()
        cur.execute(sql5)
        print(h)
        result = cur.fetchall()
        print(result)
        for row in result:
            if (row[2] == "Available" or row[2] == "Unavailable/Maintenance"
                    or row[2] == "Unavailable/Occupied"):
                MsgBox = messagebox.askquestion('Room Dirty?',
                                                'Is room dirty??')
                if MsgBox == 'yes':
                    l.config(bg="pink", fg="white")
                    makeRoomDirty(h)
                else:
                    pass
            if (row[2] == "Unavailable/Dirty"):
                MsgBox = messagebox.askquestion('Room Dirty?',
                                                'Make room Available?')
                if MsgBox == 'yes':
                    availableRoom(row, column, h, l)
                else:
                    pass

    def occupiedRoom(row, column, h, l):
        #print(label.grid_info())
        room(h, l)
        l.config(bg='blue', fg='black')
        # widget= window.grid_slaves(row=row, column=column)[0]
        # widget.configure(bg="blue",fg="black")

    def maintenanceRoom(row, column, h, l):
        #print(label.grid_info())
        # l.config(bg="red", fg="white")
        # makeRoomMaintance(h)
        # widget= window.grid_slaves(row=row, column=column)[0]
        # widget.configure(bg="red",fg="white")
        conn = sqlite3.connect('hotel.db')
        sql5 = 'SELECT * FROM Room WHERE RoomNumber=' + str(h)
        cur = conn.cursor()
        cur.execute(sql5)
        print(h)
        result = cur.fetchall()
        print(result)
        for row in result:
            if (row[2] == "Available" or row[2] == "Unavailable/Dirty"
                    or row[2] == "Unavailable/Occupied"):
                MsgBox = messagebox.askquestion('Room Maintanance?',
                                                'Room Need Maintenance?')
                if MsgBox == 'yes':
                    l.config(bg="red", fg="white")
                    makeRoomMaintance(h)
                else:
                    pass
            if (row[2] == "Unavailable/Maintenance"):
                MsgBox = messagebox.askquestion('Room Maintanance?',
                                                'Make room Available?')
                if MsgBox == 'yes':
                    availableRoom(row, column, h, l)
                else:
                    pass

    for row in range(10):  #populate room and room types

        for column in range(6):

            if row == 0:
                lable1 = Label(roomwindow,
                               text="Room Number",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable1.grid(row=0,
                            column=1,
                            sticky="nsew",
                            padx=1,
                            pady=1,
                            columnspan=8)
            elif row == 0 and column == 0:
                lable0 = Label(roomwindow, text="")
                lable0.grid(row=0, column=0, sticky="nsew", padx=1, pady=1)

            elif column == 0 and row == 1:
                lable2 = Label(roomwindow,
                               text="King Size bed",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable2.grid(row=1, column=0, sticky="nsew", padx=1, pady=1)
            elif column == 0 and row == 2:
                lable3 = Label(roomwindow,
                               text="Double Queen Bed",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable3.grid(row=2, column=0, sticky="nsew", padx=1, pady=1)
            elif row == 3 and column == 0:
                lable4 = Label(roomwindow,
                               text="Double Queen Bed With Kitchen",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable4.grid(row=3, column=0, sticky="nsew", padx=1, pady=1)
            elif row == 4 and column == 0:
                lable5 = Label(roomwindow,
                               text="Suite",
                               bg="black",
                               fg="white",
                               padx=3,
                               pady=3)
                lable5.grid(row=4, column=0, sticky="nsew", padx=1, pady=1)
            elif row == 5:
                label6 = Label(roomroot,
                               text="Key",
                               bg="Gray",
                               fg="white",
                               padx=3,
                               pady=3,
                               font="24")
                label6.grid(row=5,
                            column=1,
                            sticky="nsew",
                            padx=1,
                            pady=1,
                            columnspan=6)
            elif row == 6:
                labelG = Label(roomroot,
                               text="Maintenance",
                               bg="red",
                               fg="white")
                labelG.grid(row=6,
                            column=5,
                            sticky="nsew",
                            padx=0,
                            pady=1,
                            columnspan=1)
                labelG = Label(roomroot,
                               text="Available",
                               bg="green",
                               fg="white")
                labelG.grid(row=6,
                            column=2,
                            sticky="nsew",
                            padx=0,
                            pady=1,
                            columnspan=1)
                labelG = Label(roomroot,
                               text="Occupied",
                               bg="blue",
                               fg="white")
                labelG.grid(row=6,
                            column=3,
                            sticky="nsew",
                            padx=0,
                            pady=1,
                            columnspan=1)
                labelG = Label(roomroot, text="Dirty", bg="pink", fg="black")
                labelG.grid(row=6,
                            column=4,
                            sticky="nsew",
                            padx=0,
                            pady=1,
                            columnspan=1)
            elif row == 7:
                labelh = Label(
                    roomroot,
                    text="To check out please select occupied again",
                    font="18",
                    bg="grey",
                    fg="white")
                labelh.grid(row=7, column=2, columnspan=4)
            elif row == 8:
                labelh = Label(
                    roomroot,
                    text=
                    "To Make room Available click on the coressponding Status",
                    font="18",
                    bg="grey",
                    fg="white")
                labelh.grid(row=8, column=2, columnspan=4)
            elif row == 9:
                labelh = Label(roomroot,
                               text="To exit please close the Key window",
                               font="18",
                               bg="grey",
                               fg="white")
                labelh.grid(row=9, column=2, columnspan=4)

            else:
                h += 1  #using Menu Button to let user select status of the room
                label = Menubutton(roomwindow,
                                   text=h,
                                   bg="green",
                                   fg="white",
                                   padx=1,
                                   pady=1)
                label.grid(row=row,
                           column=column,
                           sticky="nsew",
                           padx=1,
                           pady=1)
                roomwindow.grid_columnconfigure(column, weight=1, uniform=1)
                label.menu = Menu(label)
                label["menu"] = label.menu
                label.menu.add_command(
                    label="available",
                    command=lambda h=h, row=row, column=column, l=label:
                    availableRoom(row, column, h, l))
                label.menu.add_command(
                    label="occupied",
                    command=lambda h=h, row=row, column=column, l=label:
                    occupiedRoom(row, column, h, l))
                label.menu.add_command(
                    label="dirty",
                    command=lambda h=h, row=row, column=column, l=label:
                    dirtyRoom(row, column, h, l))
                label.menu.add_command(
                    label="maintenance",
                    command=lambda h=h, row=row, column=column, l=label:
                    maintenanceRoom(row, column, h, l))

    def reloadWindow():
        conn = sqlite3.connect('hotel.db')
        sql5 = 'SELECT * FROM Room'
        cur = conn.cursor()
        cur.execute(sql5)
        result = cur.fetchall()

        for row in result:
            print(row)
            if (row[2] == "Unavailable/Occupied"):
                sql2 = 'SELECT RowX, ColumnY FROM RoomType WHERE RoomNumber =' + row[
                    0]
                cur.execute(sql2)
                roomResult = cur.fetchall()
                for temp in roomResult:
                    loadOccupiedRoom(temp[0], temp[1])
            if (row[2] == "Unavailable/Dirty"):
                sql3 = 'SELECT RowX, ColumnY FROM RoomType WHERE RoomNumber =' + row[
                    0]
                cur.execute(sql3)
                roomResult1 = cur.fetchall()
                for temp in roomResult1:
                    loadDirtyRoom(temp[0], temp[1])
            if (row[2] == "Unavailable/Maintenance"):
                sql4 = 'SELECT RowX, ColumnY FROM RoomType WHERE RoomNumber =' + row[
                    0]
                cur.execute(sql4)
                roomResult2 = cur.fetchall()
                for temp in roomResult2:
                    loadMaintenanceRoom(temp[0], temp[1])
            if (row[2] == "Available"):
                sql4 = 'SELECT RowX, ColumnY FROM RoomType WHERE RoomNumber =' + row[
                    0]
                cur.execute(sql4)
                roomResult2 = cur.fetchall()
                for temp in roomResult2:
                    loadAvailableRoom(temp[0], temp[1])

    reloadWindow()
コード例 #14
0
class Roller(Frame):
    def __init__(self, group, index):
        Frame.__init__(self, group)

        self.group = group
        self.index = index
        self.results = [0]
        self.history = []

        self.name = StringVar()
        self.dice_qty = IntVar()
        self.die_faces = IntVar()
        self.modifier = IntVar()
        self.finalmod = IntVar()
        self.results_text = StringVar()

        self.name.trace('w', self.group.mainframe.set_unsaved_title)
        self.dice_qty.trace('w', self.group.mainframe.set_unsaved_title)
        self.die_faces.trace('w', self.group.mainframe.set_unsaved_title)
        self.modifier.trace('w', self.group.mainframe.set_unsaved_title)
        self.finalmod.trace('w', self.group.mainframe.set_unsaved_title)
        self.results_text.trace('w', self.group.mainframe.set_unsaved_title)

        default_font = ('Courier', 14)

        self.menu_btn = Menubutton(self,
                                   bd=1,
                                   relief='solid',
                                   font=('Courier', 8),
                                   text='\u25e2',
                                   takefocus=1,
                                   highlightthickness=1)
        self.name_entry = Entry(self,
                                bd=1,
                                relief='solid',
                                font=('Verdana', 12),
                                width=16,
                                textvariable=self.name)

        self.dice_qty_spin = NumericSpinner(self,
                                            self.dice_qty,
                                            1,
                                            99,
                                            callback=self.reset,
                                            initial=1)
        self.die_faces_spin = NumericSpinner(
            self,
            self.die_faces,
            2,
            100,
            interval=self.group.mainframe.allow_odd.get(),
            initial=10)
        self.modifier_spin = NumericSpinner(self,
                                            self.modifier,
                                            -99,
                                            100,
                                            callback=self.apply_modifiers)
        self.finalmod_spin = NumericSpinner(self,
                                            self.finalmod,
                                            -99,
                                            100,
                                            callback=self.apply_modifiers)
        self.dice_lbl = Label(self, text=' d', font=default_font)
        self.modifier_lbl = Label(self, text='\u002b', font=default_font)
        self.finalmod_lbl = Label(self, text='\u002b', font=default_font)

        self.roll_btn = Button(self,
                               bd=0,
                               image=self.group.roll_img,
                               command=lambda: self.roll(single=True))
        self.results_entry = Entry(self,
                                   bd=0,
                                   relief='solid',
                                   font=default_font,
                                   width=0,
                                   textvariable=self.results_text,
                                   state='readonly',
                                   justify='center')

        self.menu_btn.config(menu=self.create_menu())

        self.menu_btn.grid(row=index, column=0, padx=(4, 0))
        self.name_entry.grid(row=index, column=1, padx=(4, 0))
        self.dice_qty_spin.grid(row=index, column=2, padx=(4, 0))
        self.dice_lbl.grid(row=index, column=3, padx=(0, 0))
        self.die_faces_spin.grid(row=index, column=4, padx=(0, 0))
        self.modifier_lbl.grid(row=index, column=5, padx=(6, 6))
        self.modifier_spin.grid(row=index, column=6, padx=(0, 0))
        self.roll_btn.grid(row=index, column=7, padx=(8, 0))
        self.results_entry.grid(row=index, column=8, padx=(8, 0))
        self.finalmod_lbl.grid(row=index, column=9, padx=(6, 6))
        self.finalmod_spin.grid(row=index, column=10, padx=(0, 4))

        self.name.set('Roller {}'.format(len(self.group.rollers) + 1))
        self.die_faces.set(10)
        self.results_text.set('0 = 0')

        self.grid(row=index, sticky='w', pady=4)

    def create_menu(self):
        menu = Menu(self.menu_btn,
                    tearoff=0,
                    postcommand=self.group.maintain_roller_indices)

        menu.add_command(label='Add', underline=0, command=self.add_roller)
        menu.add_command(label='Clone',
                         underline=0,
                         command=lambda: self.add_roller(clone=True))
        menu.add_command(label='Up',
                         underline=0,
                         command=lambda: self.move_roller(offset=-1))
        menu.add_command(label='Down',
                         underline=0,
                         command=lambda: self.move_roller(offset=1))
        menu.add_separator()  #  ------
        menu.add_command(label='Remove',
                         underline=0,
                         command=self.remove_roller)

        return menu

    def create_hist_record(self):
        record = {
            'dice_qty': self.dice_qty.get(),
            'die_faces': self.die_faces.get(),
            'modifier': self.modifier.get(),
            'results_text': self.results_text.get(),
            'finalmod': self.finalmod.get(),
            'timestamp': str(dt.now().time())[:8],
            'results': self.results
        }
        return record

    def add_roller(self, clone=False):
        destination_index = self.index + 1

        roller = Roller(self.group, destination_index)
        self.group.rollers.insert(roller.index, roller)

        for i in range(destination_index, len(self.group.rollers)):
            self.group.rollers[i].grid(row=i + 1)

        if clone:
            roller.name.set(self.name.get())
            roller.dice_qty.set(self.dice_qty.get())
            roller.die_faces.set(self.die_faces.get())
            roller.modifier.set(self.modifier.get())
            roller.finalmod.set(self.finalmod.get())
            roller.reset()

        for h in self.history:
            record = roller.create_hist_record()
            record['timestamp'] = h['timestamp']
            roller.history.append(record)

        roller.apply_modifiers()

        for r in self.group.rollers:
            r.lift()

        self.group.mainframe.editmenu.entryconfigure(
            self.group.mainframe.editmenu.index('end'),
            command=lambda: self.add_roller(clone=clone))
        self.group.mainframe.bind_all('<Control-r>',
                                      lambda e: self.add_roller(clone=clone))

    def move_roller(self, offset=0, destination_index=0):
        if not destination_index:
            destination_index = self.index + offset

        if destination_index >= 0:
            roller = self.group.rollers.pop(self.index)
            self.group.rollers.insert(destination_index, roller)

        self.group.maintain_roller_indices()
        self.name.set(self.name.get())

        self.group.mainframe.editmenu.entryconfigure(
            self.group.mainframe.editmenu.index('end'),
            command=lambda: self.move_roller(offset=offset))
        self.group.mainframe.bind_all(
            '<Control-r>', lambda e: self.move_roller(offset=offset))

    def remove_roller(self):
        if len(self.group.rollers) > 1:
            self.grid_remove()
            self.group.rollers.remove(self)
            self.name.set('')

    def reset(self, loading=False):
        self.results = [0 for i in range(self.dice_qty.get())]
        self.dice_qty_spin.step(0)
        self.die_faces_spin.step(0)
        self.modifier_spin.step(0)
        self.finalmod_spin.step(0)
        if not loading:
            self.apply_modifiers()
            self.group.maintain_result_widths()

    def roll(self, single=False):
        rolls = self.dice_qty.get()
        sides = self.die_faces.get()

        if self.group.mainframe.allow_odd.get() % 2 == 0 and sides % 2 != 0:
            self.die_faces.set(sides - 1)
            sides -= 1

        mod = self.modifier.get()
        fmod = self.finalmod.get()
        max_roll = sides
        min_roll = 1
        results = []

        if self.group.mainframe.use_random_org.get():
            url = 'https://www.random.org/integers/?col={0}&num={0}&min={1}&max={2}&base=10&format=plain&rnd=new'
            url = url.format(rolls, min_roll, max_roll)
            try:
                resp = urlopen(url)
                results.extend([
                    int(x) for x in str(resp.read().rstrip(),
                                        encoding='utf8').split('\t')
                ])
                sleep(0.1)
            except:
                print('Failed to use random.org, falling back to CSPRNG!')

        if not results:
            csprng = SystemRandom()
            for i in range(rolls):
                roll = csprng.randint(min_roll, sides)
                results.append(roll)

        self.results = []
        for n in results:
            if n == max_roll:
                self.results.append(n * CRIT)
            elif n == min_roll:
                self.results.append(n * FAIL)
            else:
                self.results.append(n)

        self.apply_modifiers(True)

        self.history.append(self.create_hist_record())
        hist_index = len(self.history) - 1
        if single:
            for roller in self.group.rollers:
                if roller is not self:
                    roller.history.append(roller.create_hist_record())
            self.group.navigate_history(desired_index=hist_index)

        self.group.hist_index = hist_index
        self.name.set(self.name.get())

        self.group.mainframe.editmenu.entryconfigure(
            self.group.mainframe.editmenu.index('end'),
            command=lambda: self.roll(single=single))
        self.group.mainframe.bind_all('<Control-r>',
                                      lambda e: self.roll(single=single))

    def apply_modifiers(self, rolling=False):
        fmod = self.finalmod.get()
        dmod = self.modifier.get()
        dqty = self.dice_qty.get()

        formatted_results = []
        total = 0
        for n in self.results:
            if n > CRIT:
                n = int(n / CRIT)
                n = n + dmod
                formatted_results.append('\u25b2{}'.format(str(n)))
            elif 0 < n < 1:
                n = int(n / FAIL)
                n = n + dmod
                formatted_results.append('\u25bc{}'.format(str(n)))
            else:
                n = n + dmod
                formatted_results.append(str(n))
            total += n

        s = ' + '.join(formatted_results)
        s = '{} = {}'.format(total + fmod, s)

        if not rolling and self.history:
            self.history[self.group.hist_index]['modifier'] = dmod
            self.history[self.group.hist_index]['finalmod'] = fmod
            self.history[self.group.hist_index]['results_text'] = s

        self.results_text.set(s)
        self.group.maintain_result_widths()
コード例 #15
0
class RollerGroup(LabelFrame):
    def __init__(self, mainframe, index):
        LabelFrame.__init__(self, mainframe)

        self.mainframe = mainframe
        self.index = index
        self.hist_index = 0
        self.collapsed = False
        self.rollers = []
        self.control_frame = Frame(None)
        default_font = ('Verdana', 10)

        self.name = StringVar()
        self.name.trace('w', self.mainframe.set_unsaved_title)

        self.expand_img = PhotoImage(
            data=
            b'R0lGODlhEAAQAIABAAAAAP///yH5BAEKAAEALAAAAAAQABAAAAIlhI+pq+EPHYo0TGjifRkfDYAdI33WUnZc6KmlyK5wNdMrg+dJAQA7'
        )
        self.collapse_img = PhotoImage(
            data=
            b'R0lGODlhEAAQAIABAAAAAP///yH5BAEKAAEALAAAAAAQABAAAAIfhI+pq+EPHYo0zAovlme/y3CGmJCeeWqbirEVA8dLAQA7'
        )

        self.collapse_btn = Button(self.control_frame,
                                   bd=0,
                                   image=self.collapse_img,
                                   command=self.show_hide)
        self.menu_btn = Menubutton(self.control_frame,
                                   bd=1,
                                   relief='solid',
                                   font=('Courier', 8),
                                   text='\u25e2',
                                   takefocus=1,
                                   highlightthickness=1)
        self.name_entry = Entry(self.control_frame,
                                bd=1,
                                relief='solid',
                                font=('Verdana', 12),
                                width=16,
                                textvariable=self.name)

        self.history_frame = LabelFrame(self.control_frame,
                                        bd=1,
                                        text='History',
                                        relief='solid',
                                        font=default_font,
                                        labelanchor='w')
        self.roll_frame = LabelFrame(self.control_frame,
                                     bd=1,
                                     text='Roll',
                                     relief='solid',
                                     font=default_font,
                                     labelanchor='w')

        self.roll_img = PhotoImage(
            data=
            b'R0lGODlhDgARAIABAAAAAP///yH5BAEKAAEALAAAAAAOABEAAAIkjB+Ai6C83GOy0iqjM7ltPoFhKEKeKZJadynfVa6HlbAp3ZIFADs='
        )
        self.left_arrow = PhotoImage(
            data=
            b'R0lGODlhBwANAIABAAAAAP///yH5BAEKAAEALAAAAAAHAA0AAAITjA9nkMj+Apty2lvt0jt2VYFSAQA7'
        )
        self.right_arrow = PhotoImage(
            data=
            b'R0lGODlhBwANAIABAAAAAP///yH5BAEKAAEALAAAAAAHAA0AAAITRI5gGLrnXlzT1NsidEkx/zFHAQA7'
        )

        self.roll_btn = Button(self.roll_frame,
                               bd=0,
                               image=self.roll_img,
                               height=24,
                               command=self.roll_group)
        self.hist_prev_btn = Button(
            self.history_frame,
            bd=0,
            image=self.left_arrow,
            height=24,
            width=16,
            repeatdelay=250,
            repeatinterval=100,
            command=lambda: self.navigate_history(offset=-1))
        self.hist_next_btn = Button(
            self.history_frame,
            bd=0,
            image=self.right_arrow,
            height=24,
            width=16,
            repeatdelay=250,
            repeatinterval=100,
            command=lambda: self.navigate_history(offset=1))

        self.menu_btn.config(menu=self.create_menu())

        self.collapse_btn.grid(row=0, column=0, padx=(4, 0))
        self.menu_btn.grid(row=0, column=1, padx=(4, 0))
        self.name_entry.grid(row=0, column=2, padx=(4, 0))
        self.history_frame.grid(row=0, column=3, padx=(6, 0))
        self.hist_prev_btn.grid(row=0, column=0, padx=(6, 0))
        self.hist_next_btn.grid(row=0, column=1, padx=(0, 2))
        self.roll_frame.grid(row=0, column=4, padx=(6, 4))
        self.roll_btn.grid(row=0, column=0, padx=(6, 2))

        self.config(relief='solid', labelwidget=self.control_frame)
        self.name.set('Group {}'.format(len(roller_groups) + 1))
        self.grid(row=index, padx=4, pady=4, sticky='w')

    def show_hide(self):
        if self.collapsed:
            for roller in self.rollers:
                roller.grid()
            self.collapse_btn.config(image=self.collapse_img)
            self.collapsed = False
        else:
            for roller in self.rollers:
                roller.grid_remove()
            self.collapse_btn.config(image=self.expand_img)
            width = 28 + self.collapse_btn.winfo_width(
            ) + self.menu_btn.winfo_width() + self.name_entry.winfo_width()
            self.config(height=36, width=width)
            self.collapsed = True

    def create_menu(self):
        menu = Menu(self.menu_btn,
                    tearoff=0,
                    postcommand=maintain_group_indices)

        menu.add_command(label='Add', underline=0, command=self.add_group)
        menu.add_command(label='Clone',
                         underline=0,
                         command=lambda: self.add_group(clone=True))
        menu.add_command(label='Up',
                         underline=0,
                         command=lambda: self.move_group(offset=-1))
        menu.add_command(label='Down',
                         underline=0,
                         command=lambda: self.move_group(offset=1))
        menu.add_separator()  #  -------------
        menu.add_command(label='Clear history',
                         underline=6,
                         command=self.clear_history)
        menu.add_command(label='Remove',
                         underline=0,
                         command=self.remove_group)

        return menu

    def add_group(self, clone=False):
        destination_index = self.index + 1

        group = RollerGroup(self.mainframe, destination_index)
        roller_groups.insert(group.index, group)

        for i in range(destination_index, len(roller_groups)):
            roller_groups[i].grid(row=i + 1)

        if clone:
            for roller in self.rollers:
                new_roller = Roller(group, self.rollers.index(roller))
                new_roller.name.set(roller.name.get())
                new_roller.dice_qty.set(roller.dice_qty.get())
                new_roller.die_faces.set(roller.die_faces.get())
                new_roller.modifier.set(roller.modifier.get())
                new_roller.finalmod.set(roller.finalmod.get())
                group.rollers.append(new_roller)
            group.name.set(self.name.get())
        else:
            group.rollers.append(Roller(group, 0))
            group.name.set(group.name.get())

        maintain_tabstops()

        self.mainframe.editmenu.entryconfigure(
            self.mainframe.editmenu.index('end'),
            command=lambda: self.add_group(clone=clone))
        self.mainframe.bind_all('<Control-r>',
                                lambda e: self.add_group(clone=clone))

    def move_group(self, offset=0, destination_index=0):
        if not destination_index:
            destination_index = self.index + offset

        if destination_index >= 0:
            group = roller_groups.pop(self.index)
            roller_groups.insert(destination_index, group)

        maintain_group_indices()
        self.name.set(self.name.get())

        self.mainframe.editmenu.entryconfigure(
            self.mainframe.editmenu.index('end'),
            command=lambda: self.move_group(offset=offset))
        self.mainframe.bind_all('<Control-r>',
                                lambda e: self.move_group(offset=offset))

    def clear_history(self):
        for roller in self.rollers:
            roller.reset()
            roller.history = []
        self.history_frame.config(text='History')

    def remove_group(self, override=False):
        if len(roller_groups) > 1 or override:
            self.grid_remove()
            roller_groups.remove(self)
            self.name.set('')

    def maintain_roller_indices(self):
        for roller in self.rollers:
            roller.index = self.rollers.index(roller)
            roller.grid(row=roller.index)

    def roll_group(self):
        for roller in self.rollers:
            roller.roll()

        self.navigate_history()

        self.mainframe.editmenu.entryconfigure(
            self.mainframe.editmenu.index('end'),
            command=lambda: self.roll_group())
        self.mainframe.bind_all('<Control-r>', lambda e: self.roll_group())

    def navigate_history(self, offset=0, desired_index=0):
        hist_len = len(self.rollers[0].history)
        if not hist_len:
            return

        if not desired_index:
            desired_index = self.hist_index + offset

        if desired_index >= -1 and desired_index <= hist_len:
            if desired_index == -1:
                desired_index = 0
            if desired_index == hist_len:
                desired_index = hist_len - 1
            for roller in self.rollers:
                hist_dict = roller.history[desired_index]
                roller.results = hist_dict['results']
                roller.dice_qty.set(hist_dict['dice_qty'])
                roller.die_faces.set(hist_dict['die_faces'])
                roller.modifier.set(hist_dict['modifier'])
                roller.results_text.set(hist_dict['results_text'])
                roller.finalmod.set(hist_dict['finalmod'])
                self.history_frame.config(text=hist_dict['timestamp'])
            self.hist_index = desired_index

        self.maintain_result_widths()

    def maintain_result_widths(self):
        for roller in self.rollers:
            w = len(roller.results_text.get())
            if w > 80:
                w = 80
            roller.results_entry.config(width=w)
コード例 #16
0
from tkinter import (
    Tk, Menubutton, RAISED, Menu, IntVar
)

layar = Tk()
layar.title("Menu Button")
layar.geometry("300x100")

mb = Menubutton( master=layar, text="condiment", relief=RAISED)
mb.grid()
mb.menu = Menu( master=mb, tearoff=0)

mb["menu"] = mb.menu

mayoVar = IntVar()
ketchVar = IntVar()

mb.menu.add_checkbutton(label="mayo", variable=mayoVar)
mb.menu.add_checkbutton(label="ketch", variable=ketchVar)

mb.pack()

layar.mainloop()
コード例 #17
0
from tkinter import IntVar, Menu, Menubutton, Tk

root = Tk()
root.title('Menu button example')


def menu_sel():
    """Check and report on menu selection."""
    if VAR1.get():
        print('V2 ticked')
    if VAR2.get():
        print('V3 ticked')


menu_btn = Menubutton(root, text='Choose Python Version', bg='skyblue')
menu_btn.grid(padx=20, pady=20)

menu_btn.menu = Menu(menu_btn, tearoff=0)
menu_btn['menu'] = menu_btn.menu

VAR1 = IntVar()
VAR2 = IntVar()

menu_btn.menu.add_checkbutton(label='Python V2',
                              variable=VAR1,
                              command=menu_sel)
menu_btn.menu.add_checkbutton(label='Python V3',
                              variable=VAR2,
                              command=menu_sel)
menu_btn.grid()