python GUI(tkinter)

Preface

Record the Tkinter functions used in the python system, it is convenient to find next time

Text、Entry

Attributes

(1) The function tkinter.Text.get('1.2', END), where the first parameter '1.2' refers to reading from the first row and second column ('1.0' means the first row and first column, That is, the first character), the second End represents the last character

Button

Attributes

(1) Set the font: font=('kaiti', 20)

Listbox

Features

(1) Use the "left mouse button" event to bind the object of the listbox to return the subscript of the listbox content. code show as below.

from tkinter import *

class make_list():
    def __init__(self,master):
        frame = Frame(master)
        frame.pack()

        self.list1 = None
        self.build_main_window(frame)
        self.list1.bind('<Button-1>', self.click_button)

    def click_button(self, event):
        self.curIndex = event.widget.nearest(event.y)
        print(self.curIndex)

    #display the window, calls the listbox
    def build_main_window(self, frame):
        self.build_listbox(frame)

    #listbox
    def build_listbox(self, frame):
        self.list1 = Listbox(frame)
        for item in ["one", "two", "three", "four"]:
            self.list1.insert(END, item)
        self.list1.insert(END, "a list entry")
        self.list1.pack()

if __name__ == '__main__':
    tk = Tk()
    make_list(tk)
    tk.mainloop()

Label

Attributes

(1) Length, width: width, height
(2) Alignment: justify, optional values ​​are: LEFT, RIGHT, CENTER, the default is CENTER.
(3) Set the text to display in multiple lines: wraplength, the default is 0. Note: The value is in pixels.
(4) Align the anchor, which feels easier to use than justify. Optional parameters are:'n, ne, e, se, s, sw, w, nw, or center'

Frame

Attributes

(1) Cursor is better for testing the scope. It is enough to use a "circle" parameter. When the mouse reaches the top of the frame, it becomes a circle.
(2) Relief specifies the border style. The
default value is "flat".
In addition, you can also set "sunken", "raised", "groove" or "ridge".
Note that if you want to set the border style, remember to set the borderwidth or bd option. 0 to see the border

Features

(1) The adaptive size includes internal components: frame.grid_propagate(0), false for custom, True for adaptive

grid layout

Attributes

(1) row=x,column=y: place the control on the x row and y column.
(2) columnspan: Set the number of columns that the cell spans horizontally, that is, the number of columns (width) occupied by the control; rowspan: Set the number of rows that the cell spans vertically, that is, the number of rows (height) that the control occupies.
(3) ipadx: set the size of the horizontal blank area in the control; ipady: set the size of the vertical blank area in the
control ; padx: set the reserved size of the horizontal blank area around the control ; pady: set the reserved size of the vertical blank area around the control;
( 4) sticky: The default alignment of the control in the window is centered. You can use the sticky option to specify the alignment, the values ​​that can be selected are: N/S/E/W

Features

(1) Distribute weights in the box: Experience the following code specifically, if you use grid() layout, you must try it, you should use it:

from tkinter import *

root = Tk()
root.geometry("600x400")
#设置顶级窗体的行列权重,否则子组件的拉伸不会填充整个窗体
root.rowconfigure(0,weight=1)
root.columnconfigure(0,weight=1)

frame = Frame(root,cursor = "Circle")
frame.grid(row=0,column=0,sticky=N+S+W+E)
#分配权重
frame.rowconfigure(0,weight = 1);frame.rowconfigure(1,weight = 8);frame.rowconfigure(2,weight = 1)
frame.columnconfigure(0,weight = 5);frame.columnconfigure(1,weight = 1)
labelr = Label(frame,bg="red")
labelg = Label(frame,bg = "gray")
labelb = Label(frame,bg = "blue")
labely = Label(frame,bg= "yellow")

labelr.grid(row = 0,column = 0,columnspan = 2,sticky=N+S+W+E)
labelg.grid(row = 1,column = 0,sticky=N+S+W+E)
labelb.grid(row = 1,column = 1,rowspan = 2,sticky=N+S+W+E)
labely.grid(row = 2,column = 0,sticky=N+E+W+S)
mainloop()

(2) It should be noted that all components with text will make the components larger. Therefore, if you have a label or button with text, you need to estimate the size in advance.

mysql use operation

  1. Import library
import pymysql
  1. Connect to the database
conn = pymysql.connect(
    host= localhost,   #服务器
    port=3306,
    user='famousCar',   #服务器登录user 
    password='123123',
    db='famousCar',     #服务器数据库
    charset='utf8',
)
  1. Add data to the database
nn = '123';np = '123'
cur = conn.cursor()
cur.execute('insert into login values (%s,%s);',[nn,np])	#字符串的语法和sql语句相似
conn.commit()			#注意必须commit
cur.close()				#使用完别忘了close

xlsx file operations

  1. xlsx file import
    needs to import two modules
from openpyxl import Workbook,load_workbook
#打开excel
    wb = load_workbook('info.xlsx')
    sh = wb['Sheet']
    global count_Num,Max_Num,all_data
    for i in sh.values:
        count_Num += 1
        Max_Num += 1
        all_data.append(list(i))
  1. xlsx file export
	# 在内存中创建一个workbook对象,而且会至少创建一个 worksheet
        wb = Workbook()
        #获取当前活跃的worksheet,默认就是第一个worksheet
        ws = wb.active
        for row in range(1,len(all_data)+1):
            for col in range (1,8):
                if(col == 1):
                    ws.cell(row = row,column = col).value = row
                elif col == 3:
                    ws.cell(row = row,column = col).value = float(all_data[row-1][col-1])
                else:
                    ws.cell(row = row,column = col).value = all_data[row-1][col-1]
        #保存
        wb.save(filename="./info.xlsx")

other

1. Mouse binding event <MouseWheel>

Triggered when the mouse wheel is scrolled (supports WIN and mac systems, Linux refers to Button). Format: *.bind('',fun)
2. Check whether there are any characters after removing all blank characters:

elif len(''.join(name1.split())) == 0:
	tk.messagebox.showerror('错误','请输入名称')

3. Check whether it is all Chinese:

def is_all_chinese(self,strs):
     for i in strs:
         if not '\u4e00' <= i <= '\u9fa5':
             return False
     return True

4. Check whether it is a positive integer or floating point number

	def is_number(num):
        s = str(num)
        if s.count('.') == 1:  # 小数
            new_s = s.split('.')
            left_num = new_s[0]
            right_num = new_s[1]
            if right_num.isdigit():
                if left_num.isdigit():
                    return True
        elif s.count(".") == 0:  # 整数
            if s.isdigit():
                return True
        return False

5. Add a prompt box

tkinter.messagebox.showinfo('提示','人生苦短')

6. Set the png picture as the window icon

window = tk.Tk()
window.iconphoto(True, tk.PhotoImage(file='./image/icon.png'))

7. Set the window size, centering and not adjustable size

def set_win_center(root, curWidth, curHight):
    '''
    设置窗口大小,并居中显示
    :param root:主窗体实例
    :return:无
    '''
    # 获取屏幕宽度和高度
    scn_w, scn_h = root.maxsize()

    # 计算中心坐标
    cen_x = (scn_w - curWidth) / 2
    cen_y = (scn_h - curHight) / 2

    # 设置窗口初始大小和位置
    size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y)
    
    root.resizable(0,0)								#设置大小不可调节
    root.geometry(size_xy)

to sum up

Current implementation, still going on:
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44223946/article/details/110352473