Advertisement
Guest User

Untitled

a guest
Jul 12th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.11 KB | None | 0 0
  1. from tkinter import *
  2. from tkinter.ttk import *
  3. import pymysql.cursors
  4.  
  5. class DBTest:
  6.     #Initiates thingies we'll use
  7.     def __init__(self, root):
  8.         self._create_tabs()
  9.         self._layout()
  10.  
  11.     def _create_tabs(self):
  12.         self.frame = Frame(root) # Main Frame
  13.         self.nb = Notebook(self.frame) # The 'tab-thingy'
  14.  
  15.         # Create main tabs
  16.         customer = Frame(self.nb)
  17.         order = Frame(self.nb)
  18.         product = Frame(self.nb)
  19.         # Create customer NB
  20.         self.customer = Notebook(customer)        
  21.         # Create Customer-tabs
  22.         customer.insert = Frame(self.customer)
  23.         customer.select = Frame(self.customer)
  24.         customer.selAll = Frame(self.customer)
  25.         customer.delete = Frame(self.customer)
  26.         self._customer_insert_frame(customer.insert)
  27.         self._customer_select_frame(customer.select)
  28.         self._customer_selAll_frame(customer.selAll)
  29.         self._customer_delete_frame(customer.delete)
  30.        
  31.         # Create order NB
  32.         self.order = Notebook(order)
  33.         # Create order-tabs
  34.         order.insert = Frame(self.order)
  35.         order.select = Frame(self.order)
  36.         order.selAll = Frame(self.order)
  37.         #self._order_insert_frame(order.insert)
  38.         #self._order_select_frame(order.select)
  39.         #self._order_selAll_frame(order.selAll)
  40.  
  41.         # Adds the tabs to the notebook
  42.         self.nb.add(customer, text="Customer")
  43.         self.nb.add(order, text="Order")
  44.         self.nb.add(product, text="Product")
  45.         self.customer.add(customer.insert, text="Insert")
  46.         self.customer.add(customer.select, text="Select")
  47.         self.customer.add(customer.selAll, text="Select ALL")
  48.         self.customer.add(customer.delete, text="Delete Cust.")
  49.         self.order.add(order.insert, text="Insert")
  50.         self.order.add(order.select, text="Select")
  51.         self.order.add(order.selAll, text="Select ALL")
  52.  
  53.     def _layout(self):
  54.         # Layout
  55.         self.frame.grid(row=0, column=0, sticky=(N,S,W,E))
  56.         self.nb.grid(row=0, column=0, sticky=(N,S,W,E))
  57.         self.customer.grid(row=0, column=0, columnspan=2, sticky=(N,S,W,E), pady=5)
  58.         self.order.grid(row=0, column=0, columnspan=2, sticky=(N,S,W,E), pady=5)
  59.         # Resize rules
  60.         root.columnconfigure(0, weight=1)
  61.         root.rowconfigure(0, weight=1)
  62.         self.frame.columnconfigure(0, weight=2)
  63.         self.frame.rowconfigure(0, weight=2)
  64.  
  65.     def _customer_insert_frame(self, insert):
  66.         # Creates the Entry boxes to get data
  67.         insert.name = Entry(insert)
  68.         insert.address = Entry(insert)
  69.         insert.phone = Entry(insert)
  70.         # Makes a label and puts things out on the screen.
  71.         Label(insert, text="Name: ").grid(row=0, column=0, sticky=E)
  72.         insert.name.grid(row=0, column=1, sticky=W)
  73.         Label(insert, text="Address: ").grid(row=1, column=0, sticky=E)
  74.         insert.address.grid(row=1, column=1, sticky=W)
  75.         Label(insert, text="Phone: ").grid(row=2, column=0, sticky=E)
  76.         insert.phone.grid(row=2, column=1, sticky=W)
  77.         # Using 'lambda: ' to prevent prepare_insert from running before we want it to.
  78.         insert.submit_button = Button(insert, text="Submit", command=lambda: self.customer_prepare_insert(insert))
  79.         insert.submit_button.grid(row=4, column=0, columnspan=2)
  80.         insert.text = Text(insert, width=30, height=4, wrap=WORD)
  81.         insert.text.grid(row=5,column=0,columnspan=2)
  82.  
  83.     def customer_prepare_insert(self, insert):
  84.         # Gets values from the Entry boxes above.
  85.         name = insert.name.get()
  86.         address = insert.address.get()
  87.         phone = insert.phone.get()
  88.         # Checks if every field has something in them. (Does not check if only a space)
  89.         if not all((name, address, phone)):        
  90.             insert.text.config(state=NORMAL)
  91.             insert.text.delete(0.0, END)
  92.             insert.text.insert(0.0, "Need to enter something in all boxes.")
  93.             insert.text.config(state=DISABLED)
  94.         # If every field is not None, do the query
  95.         else:
  96.             # Returns values entered if successful
  97.             # Else it returns the error message.
  98.             inserted = self.add_to_DB(name, address, phone)
  99.             insert.text.config(state=NORMAL)
  100.             insert.text.delete(0.0, END)
  101.             insert.text.insert(0.0, inserted)
  102.             insert.text.config(state=DISABLED)
  103.  
  104.     def _customer_select_frame(self, select):
  105.         # Create the Entry boxes
  106.         select.sID = Entry(select)
  107.         select.name = Entry(select)
  108.         select.address = Entry(select)
  109.         select.phone = Entry(select)
  110.        
  111.         # Puts them out on the frame
  112.         Label(select, text="Search for Databasedata\nenter at least 1 searchfield").grid(row=0, column=0, columnspan=2)
  113.         Label(select, text="Search ID:").grid(row=1, column=0, sticky=E)
  114.         select.sID.grid(row=1, column=1, sticky=W)
  115.         Label(select, text="Search Name:").grid(row=2, column=0, sticky=E)
  116.         select.name.grid(row=2, column=1, sticky=W)
  117.         Label(select, text="Search address").grid(row=3, column=0, sticky=E)
  118.         select.address.grid(row=3, column=1, sticky=W)
  119.         Label(select, text="Search phone").grid(row=4, column=0, sticky=E)
  120.         select.phone.grid(row=4, column=1, sticky=W)
  121.         # Using lambda again on the button to not make it do the
  122.         # prepare before we actually click the button
  123.         select.submit_button = Button(select, text="Submit", command=lambda: self.customer_prepare_select(select))
  124.         select.submit_button.grid(row=5, column=0, columnspan=2)
  125.         select.text = Text(select, width=30, height=10, wrap=WORD)
  126.         select.text.grid(row=6,column=0,columnspan=2)
  127.  
  128.     def customer_prepare_select(self, select):
  129.         # Get value from the search fields.
  130.         sID = select.sID.get()
  131.         name = select.name.get()
  132.         address = select.address.get()
  133.         phone = select.phone.get()
  134.         args = {}
  135.         stmt = ""
  136.         # Checks at least one have data. (Does not check if only a space)
  137.         if sID != "" or name != "" or address != "" or phone != "":
  138.             # If at least one have data we check which
  139.             # one and adds the string for the query
  140.             if sID != "":
  141.                 args['ID'] = "id='"+sID+"' AND "
  142.             if name != "":
  143.                 args['name'] = "name='"+name+"' AND "
  144.             if address != "":
  145.                 args['address'] = "address='"+address+"' AND "
  146.             if phone != "":
  147.                 args['phone'] = "phone='"+phone+"'"
  148.             for key, value in args.items():
  149.                 stmt += value
  150.             # Removes the last ' AND '
  151.             stmt = stmt[:-5]
  152.             sql = "SELECT * FROM CUSTOMER WHERE {val}".format(val=stmt)
  153.             db_result = self.get_from_DB(sql)
  154.             textBox = ""
  155.             # If we get rows back
  156.             if db_result:
  157.                 # Iterates for all rows gotten
  158.                 for key in db_result:
  159.                     textBox += "ID: {id} Name: {name}\nAddress: {address}\nPhone: {phone}\n\n".format(id=key['id'], name=key['name'], address=key['address'], phone=key['phone'])
  160.             # If we searched for an entry that didnt exist
  161.             else:
  162.                 textBox = "Could not find what you searched for."
  163.         # If we enter no value in any box.
  164.         else:
  165.             textBox = "Must insert at least one value."
  166.  
  167.         # Updates the textfield
  168.         select.text.config(state=NORMAL)
  169.         select.text.delete(0.0, END)
  170.         select.text.insert(0.0, textBox)
  171.         select.text.config(state=DISABLED)
  172.  
  173.     def _customer_selAll_frame(self, selAll):
  174.         #Create the button to show everything
  175.         Label(selAll, text="Fetch all entries?").grid(row=0, column=0, sticky=E)
  176.         selAll.submit_button = Button(selAll, text="Fetch!", command=lambda: self.customer_select_all_DB(selAll))
  177.         selAll.submit_button.grid(row=0, column=1, sticky=W)
  178.         selAll.text = Text(selAll, width=30, height=18, wrap=WORD)
  179.         selAll.text.grid(row=1, column=0, columnspan=2)
  180.  
  181.     def customer_select_all_DB(self, selAll):
  182.         sql = "SELECT * from CUSTOMER"
  183.         # Gets all entries from the DB
  184.         db_result = self.get_from_DB(sql)
  185.         textBox = ""
  186.         # If we get result returned
  187.         if db_result:
  188.             # Iterates for every Row
  189.             for key in db_result:
  190.                 textBox += "ID: {id} Name: {name}\nAddress: {address}\nPhone: {phone}\n\n".format(id=key['id'], name=key['name'], address=key['address'], phone=key['phone'])
  191.         # If no entries was found in the DB
  192.         else:
  193.             textBox = "There's nothing in the Database or some error n shit."
  194.         # Updates the textfield
  195.         selAll.text.config(state=NORMAL)
  196.         selAll.text.delete(0.0, END)
  197.         selAll.text.insert(0.0, textBox)
  198.         selAll.text.config(state=DISABLED)
  199.  
  200.     def _customer_delete_frame(self, delete):
  201.         Label(delete, text="Delete a user with the dropdown menu").grid(row=0, column=0, columnspan=2, sticky=E)
  202.         sql = "SELECT name FROM customer"
  203.         users = self.get_from_DB(sql)
  204.         delete.result = []
  205.         if users:
  206.             for key in users:
  207.                 delete.result.append(key['name'])
  208.         delete.result.sort()
  209.         delete.result.insert(0, "None")
  210.         delete.var = StringVar()
  211.         delete.var.set("None")
  212.         delete.menu = OptionMenu(delete, delete.var, *delete.result)
  213.         delete.menu.grid(row=1, column=0)
  214.         delete.submit_button = Button(delete, text="DELETE!", command=lambda: self.customer_delete_from_DB(delete))
  215.         delete.submit_button.grid(row=2)
  216.         delete.update_button = Button(delete, text="Update List", command=lambda: self.rebuild_window())
  217.         delete.update_button.grid(row=4)
  218.         delete.text = Text(delete, width=30, height=15, wrap=WORD)
  219.         delete.text.grid(row=3, column=0, columnspan=2)
  220.  
  221.     def customer_delete_from_DB(self, delete):
  222.         name = delete.var.get()
  223.         column = "name"
  224.         tab = "customer"
  225.         x = self.delete_from_DB(column, tab, name)
  226.         delete.text.delete(0.0, END)
  227.         delete.text.insert(0.0, x)
  228.  
  229.  
  230.     def delete_from_DB(self, column, tab, value):
  231.         # Making the query
  232.         # Takes the tab (order, customer, products) and which column (name, id, whatever)
  233.         # and lastly the value of that column. This is to re-use this delete code for other tabs.
  234.         sql = "DELETE FROM {tab} WHERE {column}='{value}'".format(tab=tab, column=column, value=value)
  235.         # Connection config
  236.         connection = self.db_settings()
  237.         # Try to do the thing
  238.         try:
  239.             with connection.cursor() as cursor:
  240.                 # Executes the delete-query
  241.                 cursor.execute(sql)
  242.                 #Commit the changes
  243.                 connection.commit()
  244.                 # Checks how many rows that was affected
  245.                 result = cursor.rowcount
  246.                 # If 1 (row deleted) then show message.
  247.                 if result == 1:
  248.                     result = "{name} from {tab}-tab has been deleted from the Database.".format(name=value, tab=tab)
  249.                 # If 0, no rows affected, thus nothing deleted.
  250.                 elif result == 0:
  251.                     result = "Nothing deleted."
  252.                 else:
  253.                     result = "Something weird happened. More than 1 row"
  254.  
  255.         except Exception as e:
  256.             if e.args[0] == 1451:
  257.                 result = "The entry you try to remove is tied to an order."
  258.             else:
  259.                 result = e
  260.         finally:
  261.             connection.close()
  262.  
  263.         # Return value
  264.         return result
  265.  
  266.     def add_to_DB(self, *args): # args are name, address, phone
  267.         # Connection config
  268.         connection = self.db_settings()
  269.         #Inserting the data
  270.         try:
  271.             # Adds it to DB
  272.             with connection.cursor() as cursor:
  273.                 # Makes it into an SQL query
  274.                 sql = "INSERT INTO CUSTOMER (name, address, phone) VALUES ('{name}', '{address}', '{phone}')".format(name=args[0],address=args[1],phone=args[2])
  275.                 cursor.execute(sql)
  276.                 # Comit the query
  277.                 connection.commit()
  278.                 result = "Data added\nName: {name}\nAddress: {address}\nPhone: {phone}".format(name=args[0],address=args[1],phone=args[2])
  279.  
  280.         except Exception as error:
  281.             code, message = error.args
  282.             if code == 1062:
  283.                 result = "A person with the name '" +args[0]+ "' already exists in the Database."
  284.             else:
  285.                 result = error
  286.         finally:
  287.             connection.close()
  288.         # Returns whatever result we got
  289.         return result
  290.  
  291.     def get_from_DB(self, sql):
  292.         # Connection config
  293.         connection = self.db_settings()
  294.         # Try to get data
  295.         try:
  296.             with connection.cursor() as cursor:
  297.                 # The query from prepare_select()
  298.                 cursor.execute(sql)
  299.                 result = cursor.fetchall()
  300.         except Exception as e:
  301.             result = e
  302.         finally:
  303.             connection.close()
  304.         return result
  305.  
  306.     # Destroys all windows, and rebuilds.
  307.     # Got tired of trying other ways.
  308.     def rebuild_window():
  309.         self.frame.destroy()
  310.         self._create_tabs()
  311.         self._layout()
  312.  
  313.     ##########
  314.     #The settings for the database, change this.
  315.     ##########
  316.     def db_settings(self):
  317.         connection = pymysql.connect(host='',
  318.                                     user='',
  319.                                     password='',
  320.                                     db='',
  321.                                     charset='utf8',
  322.                                     cursorclass=pymysql.cursors.DictCursor)
  323.         return connection
  324.  
  325.  
  326. root = Tk()
  327. # Makes window not resizeable.
  328. root.resizable(0,0)
  329. # Window size
  330. root.geometry("260x390")
  331. # Title on the window
  332. root.title("GUI Test :>")
  333. # "activates"(words pls) the mainClass
  334. app = DBTest(root)
  335. # Main loop for the tkinder
  336. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement