python tk实践

2018-08-22  本文已影响0人  王的星球
import time
from tkinter import scrolledtext
from tkinter import *

import pymssql

testdbinfo={
    'server': "0.0.0",
    'port': '9988',
    'user': "username",
    'password': 'passwd'
}

class App(Frame):
    def __init__(self, master=None):
        self.master = master
        super().__init__(master)
        master.title("卡号生成工具")
        self.pack()

        ##创建一个菜单栏,这里我们可以把他理解成一个容器,在窗口的上方
        menubar = Menu(master)
        master.config(menu=menubar)

        ##定义一个空菜单单元
        filemenu = Menu(menubar, tearoff=0)

        ##将上面定义的空菜单命名为`File`,放在菜单栏中,就是装入那个容器中
        menubar.add_cascade(label='File', menu=filemenu)

        ##在`File`中加入`New`的小菜单,即我们平时看到的下拉菜单,每一个小菜单对应命令操作。
        ##如果点击这些单元, 就会触发`do_job`的功能
        filemenu.add_command(label='生成CardNO', command=self.showcardui)
        filemenu.add_command(label='账户加值', command=self.showaccountui)  ##同样的在`File`中加入`Open`小菜单
        filemenu.add_command(label='Save', command=None)  ##同样的在`File`中加入`Save`小菜单

        filemenu.add_separator()  ##这里就是一条分割线

        ##同样的在`File`中加入`Exit`小菜单,此处对应命令为`window.quit`
        filemenu.add_command(label='Exit', command=quit)

        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)


        self.cardui = CardUI(container, self)
        self.cardui.grid(row=0, column=0, sticky="nsew")
        self.accountui = AccountUI(container, self)
        self.accountui.grid(row=0, column=0, sticky="nsew")
        self.showaccountui()

    def showcardui(self):
        self.master.maxsize(550, 350)
        self.master.update()
        self.cardui.tkraise()

    def showaccountui(self):
        self.master.maxsize(300, 100)
        self.master.update()
        self.accountui.tkraise()


class CardUI(Frame):
    def __init__(self, parent, root):
        super().__init__(parent)
        banklistframe = LabelFrame(self, width=350, height=350, text="银行列表")
        banklistframe.grid(row=0, column=1, sticky=E + W)

        cardnolistframe = Frame(self, width=350, height=350)
        cardnolistframe.grid(row=0, column=2, sticky=E + W)

        xscrollbar = Scrollbar(banklistframe, orient='horizontal')
        yscrollbar = Scrollbar(banklistframe)
        self.listbox = Listbox(banklistframe, height=15, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
        self.listbox.bind('<<ListboxSelect>>', self.generatecardno)
        self.listbox.grid(row=1, column=0, columnspan=3, ipadx=15, ipady=15, sticky=E + W)
        xscrollbar.config(command=self.listbox.xview)
        yscrollbar.config(command=self.listbox.yview)
        xscrollbar.grid(row=2, column=0, columnspan=3, sticky=E + W)
        yscrollbar.grid(row=1, column=3, sticky=S + N)

        self.cardnolist = scrolledtext.ScrolledText(cardnolistframe)
        self.cardnolist.grid(ipadx=15, ipady=15)
        self.generatebankcardno()

    def generatebankcardno(self):
        bankinfos = self.excute("select bankid,name from Ppdai_Pay_Trade_Basis..Bank")
        for bankinfo in bankinfos:
            self.listbox.insert(END, "%s(bankid:%s)" % (bankinfo['name'], bankinfo['bankid']))

    def generatecardno(self, event):
        bank = self.listbox.get(self.listbox.curselection())
        bankid = re.search(':(\d+)', bank).group(1)
        cardbinsql = 'select CardBin,CardLength from Ppdai_Pay_Trade_Basis..BankCardBin where bankid=%s' % bankid
        cardbins = self.excute(cardbinsql)
        cardnos = []
        for cardbin in cardbins:
            cardbinlen = len(cardbin['CardBin'])
            cardlength = cardbin['CardLength']
            millis = int(round(time.time() * 1000))
            startindex = 13 - cardlength + cardbinlen
            if cardlength - cardbinlen > 13:
                cardno = '%s%s' % (cardbin['CardBin'], '0' * startindex + str(millis))
            else:
                cardno = '%s%s' % (cardbin['CardBin'], str(millis)[startindex:])
            cardnos.append(cardno)
        if len(cardnos) == 0:
            cardnos.append("此银行暂时没有录入卡BIN")

        cardnotext = "\n".join(cardnos)
        self.cardnolist.delete('1.0', END)
        self.cardnolist.insert(INSERT, cardnotext)

    def excute(self, sql):
        server = testdbinfo.get("server")
        port = testdbinfo.get("port")
        user = testdbinfo.get("user")
        password = testdbinfo.get("password")
        db = pymssql.connect(server=server, port=port, user=user, password=password)
        cursor = db.cursor(as_dict=True)
        cursor.execute(sql)
        query_list = cursor.fetchall()
        db.commit()
        db.close()

        return query_list


class AccountUI(Frame):
    def __init__(self, parent, root):
        super().__init__(parent)
        self.userid = StringVar()
        frame = Frame(self)
        frame.grid(row=1, column=1)
        inputframe = Frame(frame)
        inputframe.grid(row=0, column=0, padx=10, pady=10)
        Label(inputframe, text="UserID").grid(row=0, column=0, sticky="nsew")
        Entry(inputframe, textvariable=self.userid).grid(row=0, column=1, sticky="nsew")
        btnfram = Frame(frame)
        btnfram.grid(row=1, column=0, padx=10, pady=10)
        Button(btnfram, text="PPD充值").grid(row=0, column=0, sticky="nsew")
        Button(btnfram, text="CMB充值").grid(row=0, column=2, sticky="nsew")

        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(2, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(2, weight=1)


if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

cx_Freeze打包exesetup.py文件

from cx_Freeze import setup, Executable
import os
base = None

build_exe_options = {
        'packages': ['tkinter', 'pymssql', '_mssql', 'decimal', 'uuid'],
        'excludes': [],
        # 'includes': [
        #         r'C:\Users\xuyulong\AppData\Local\Programs\Python\Python36-32\DLLs\tcl86t.dll',
        #         r'C:\Users\xuyulong\AppData\Local\Programs\Python\Python36-32\DLLs\tk86t.dll'
        # ]
}
os.environ['TCL_LIBRARY'] = r'C:\Users\xuyulong\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\xuyulong\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(name='<程序名>',
      version='0.0.1.0',
      description='<程序描述>',
      options={'build_exe': build_exe_options},
      executables=[Executable('test.py', base='Win32GUI', requires=['matplotlib'])])
上一篇下一篇

猜你喜欢

热点阅读