前言:记录最基本知识和一些简单的例子。
先写一版,后面有时间,自己在回顾温习,在详细写文章。
1. button操作
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('200x200')
var = tk.StringVar()
l = tk.Label(window, textvariable=var,bg='red',font=('Arial',12),width=15,height=2)
l.pack()
on_hit = False
def hit_me():
global on_hit
if on_hit==False:
on_hit = True
var.set("you hit "
"me")
else:
on_hit = False
var.set("")
b=tk.Button(window,text='hit me',width=15,height=2,command=hit_me)
b.pack()
window.mainloop()
2.文本插入
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('200x200')
e = tk.Entry(window,show='')
e.pack()
def insert_point():
var = e.get()
t.insert('insert',var)
def insert_end():
var = e.get()
t.insert('end',var)
# t.insert(1.2,var) #第一行第二位
b1=tk.Button(window,text='insert point',width=15,height=2,command=insert_point)
b1.pack()
b2=tk.Button(window,text='insert end',command=insert_end)
b2.pack()
# var = tk.StringVar()
t = tk.Text(window,height=2)
t.pack()
window.mainloop()
3.listbox
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('300x300')
var1 =tk.StringVar()
l = tk.Label(window, bg="yellow", width=4, textvariable=var1)
l.pack()
def insert_point():
value = lb.get(lb.curselection())
var1.set(value)
b1=tk.Button(window,text='insert point',width=15,height=2,command=insert_point)
b1.pack()
var2 = tk.StringVar()
var2.set((32,35,65,75))
lb = tk.Listbox(window,listvariable=var2)
list_items = [1,2,3,4]
for item in list_items:
lb.insert("end",item)
lb.insert(1,'first') # 下标插入
lb.insert(2,'dsfsdf')
lb.delete(2)
lb.pack()
window.mainloop()
获取list值:lb.get(lb.curselection())
4.Radiobutton
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('300x300')
var =tk.StringVar()
l = tk.Label(window, bg="yellow", width=20, text='empty')
l.pack()
def print_selection():
l.config(text = 'you have selected '+ var.get())
r1 = tk.Radiobutton(window,text='Option A',
variable=var,value='A',
command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window,text='Option B',
variable=var,value='B',
command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window,text='Option C',
variable=var,value='C',
command=print_selection)
r3.pack()
window.mainloop()
5.scale
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('300x300')
var =tk.StringVar()
l = tk.Label(window, bg="yellow", width=20, text='empty')
l.pack()
def print_selection(v):
l.config(text = 'you have selected '+ v)
s =tk.Scale(window, label = 'try me',from_=5, to=11, orient=tk.HORIZONTAL,
length = 200,showvalue=1,tickinterval=3,resolution=0.01,command
=print_selection)
s.pack()
window.mainloop()
6.Checkbutton
import tkinter as tk
window = tk.Tk()
window.title('haoge')
window.geometry('300x300')
var =tk.StringVar()
l = tk.Label(window, bg="yellow", width=20, text='empty')
l.pack()
def print_selection():
if(var1.get()==1)&(var2.get()==0):
l.config(text='I love only Python ')
elif(var1.get()==0)&(var2.get()==1):
l.config(text='I love only C++ ')
elif (var1.get() == 0) & (var2.get() == 0):
l.config(text='I do not love either ')
else:
l.config(text='I love both ')
var1 =tk.IntVar()
var2 =tk.IntVar()
c1 =tk.Checkbutton(window,text='Pathon',variable=var1,onvalue=1,offvalue=0,
command=print_selection)
c2 =tk.Checkbutton(window,text='C++',variable=var2,onvalue=1,offvalue=0,
command=print_selection)
c1.pack()
c2.pack()
window.mainloop()
7.canvas
import tkinter as tk
#画布
window = tk.Tk()
window.title('haoge')
window.geometry('600x600')
canvas=tk.Canvas(window,bg='blue',height=300,width=300)
image_file = tk.PhotoImage(file='C:\\Users\\jiangjiahao\\Desktop\\1.png')
image = canvas.create_image(10,0,anchor='center',image=image_file)
x0,y0,x1,y1=50,50,80,80
line = canvas.create_line(x0,y0,x1,y1)
oval = canvas.create_line(x0,y0,x1,y1,fill='red')
arc = canvas.create_arc(x0+30,y0+30,x1+30,y1+30,start=0,extent=180) #扇形
rect = canvas.create_rectangle(x0+80,y0+30,x1+30,y1+30) #矩形
canvas.pack()
def moveit():
canvas.move(rect,0,6)
b = tk.Button(window,text='move',command=moveit).pack()
window.mainloop()
简单的工作设计:
from tkinter import *
import hashlib
import json
import urllib.request
import pymysql
import time
LOG_LINE_NUM = 0
class MY_GUI():
def __init__(self, init_window_name):
self.init_window_name = init_window_name
#设置窗口
def set_init_window(self):
self.init_window_name.title("wallet_v1.0") #窗口名
# self.init_window_name.geometry('320x160+10+10') #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置
self.init_window_name.geometry('1068x681+10+10')
#self.init_window_name["bg"] = "pink" #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887
#self.init_window_name.attributes("-alpha",0.9) #虚化,值越小虚化程度越高
#标签
self.init_data_label = Label(self.init_window_name, text="填写邮箱")
self.init_data_label.grid(row=0, column=0)
self.result_data_label = Label(self.init_window_name, text="输出结果")
self.result_data_label.grid(row=0, column=12)
self.wallet_data_label = Label(self.init_window_name, text="设置电子钱包金额")
self.wallet_data_label.grid(row=7, column=0)
self.log_label = Label(self.init_window_name, text="日志")
self.log_label.grid(row=12, column=0)
#文本框
self.init_data_Text = Text(self.init_window_name, width=60, height=15) #原始数据录入框
self.init_data_Text.grid(row=1, column=0, rowspan=5, columnspan=10)
self.wallet_data_Text = Text(self.init_window_name, width=60, height=6) # 电子钱包金额录入框
self.wallet_data_Text.grid(row=7, column=0, rowspan=5, columnspan=10)
self.result_data_Text = Text(self.init_window_name, width=65, height=49) #处理结果展示
self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
self.log_data_Text = Text(self.init_window_name, width=66, height=9) # 日志框
self.log_data_Text.grid(row=13, column=0, columnspan=10)
#按钮
self.str_test1_setwallet_button = Button(self.init_window_name, text="设置钱包余额(第一套)", bg="lightblue", width=18, command=self.query_wallet) # 调用内部方法 加()为直接调用
self.str_test1_setwallet_button.grid(row=1, column=10)
self.str_test2_setwallet_button = Button(self.init_window_name, text="设置钱包余额(第二套)", bg="lightblue", width=18, command=self.query_wallet2) # 调用内部方法 加()为直接调用
self.str_test2_setwallet_button.grid(row=2, column=10)
def f_email(self):
global userId1
email = self.init_data_Text.get(1.0, END)[:-1].strip()
# print("email =", email)
url = ''
values = ({
"header": {
"domain": "",
"method": "queryMemUserByEmail",
"service": "com.globalegrow.mmember.spi.inter.IMemUserBaseInnerService",
"version": "1.0.0",
"url": "",
"tokenId": "487d842de4e1c9b9c99ac868c7af15a4"
},
"body": {
"siteCode": "GB",
"emailList": [email]
}
})
# print(values)
jdata = json.dumps(values).encode(encoding='UTF8') # 对数据进行JSON格式化编码
req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据
req.add_header("Content-Type", "application/json")
response = urllib.request.urlopen(req) # 发送页面请求
content = response.read()
py_data = json.loads(content)
# print(py_data)
a = json.loads(py_data.get("body"))
try:
userId1 = a['data'][0]['userId']
except:
self.write_log_to_Text("INFO:获取信息空或钱包不存在,请重填邮箱。")
def DB1(self):
global eff_money
walletnum = self.wallet_data_Text.get(1.0, END)[:-1].strip()
host = ''
post =
user = 'java-service'
passwd = ''
db = 'pay'
sq_setwallet = "UPDATE pay_wallet SET pay_wallet.effective_amount=%s,amount_hash='' WHERE user_id='%s';" % (
walletnum, userId1)
connect1 = pymysql.connect(host=host, port=post, user=user, passwd=passwd, db=db, charset='utf8')
cursor1 = connect1.cursor()
cursor1.execute(sq_setwallet)
connect1.commit() # 提交事务,改变数据的时候加这个
# status1 = cursor1.fetchall()
cursor1.close()
sq = "SELECT effective_amount FROM pay.pay_wallet WHERE user_id='%s';" %userId1
connect = pymysql.connect(host=host, port=post, user=user, passwd=passwd, db=db, charset='utf8')
cursor = connect.cursor()
cursor.execute(sq)
connect.commit() # 提交事务,改变数据的时候加这个
eff_money = cursor.fetchall()
cursor.close()
#功能函数
def query_wallet(self):
email = self.init_data_Text.get(1.0, END)[:-1].strip()
self.f_email()
if email:
try:
self.DB1()
self.result_data_Text.delete(1.0, END)
self.result_data_Text.insert(1.0, "电子钱包余额设置成功,")
self.result_data_Text.insert(2.0, "电子钱包余额:")
self.result_data_Text.insert(3.0, eff_money)
self.write_log_to_Text("INFO:设置电子钱包余额success")
except:
self.result_data_Text.delete(1.0, END)
self.result_data_Text.insert(1.0, "设置电子钱包余额失败")
else:
self.write_log_to_Text("ERROR:邮箱未填写~~。")
###.............................................................................................
def f_email2(self):
global userId2
email = self.init_data_Text.get(1.0, END)[:-1].strip()
url = ''
values = ({
"header": {
"domain": "",
"method": "queryMemUserByEmail",
"service": "com.globalegrow.mmember.spi.inter.IMemUserBaseInnerService",
"version": "1.0.0",
"url": "",
"tokenId": "9c17830f2e3c20e61948653d0697be8f"
},
"body": {
"siteCode": "GB",
"emailList": [email]
}
})
# print(values)
jdata = json.dumps(values).encode(encoding='UTF8') # 对数据进行JSON格式化编码
req = urllib.request.Request(url, jdata) # 生成页面请求的完整数据
req.add_header("Content-Type", "application/json")
response = urllib.request.urlopen(req) # 发送页面请求
content = response.read()
py_data = json.loads(content)
# print(py_data)
a = json.loads(py_data.get("body"))
try:
userId2 = a['data'][0]['userId']
except:
self.write_log_to_Text("INFO:获取信息空或钱包不存在,请重填邮箱。")
def DB2(self):
global eff_money2
walletnum = self.wallet_data_Text.get(1.0, END)[:-1].strip()
host2 = ''
post2 = 3307
user2 = 'java-service'
passwd2 = ''
db2 = 'pay'
sq_setwallet = "UPDATE pay_wallet SET pay_wallet.effective_amount=%s,amount_hash='' WHERE user_id='%s';" % (
walletnum, userId2)
connect1 = pymysql.connect(host=host2, port=post2, user=user2, passwd=passwd2, db=db2, charset='utf8')
cursor1 = connect1.cursor()
cursor1.execute(sq_setwallet)
connect1.commit() # 提交事务,改变数据的时候加这个
# status1 = cursor1.fetchall()
cursor1.close()
sq = "SELECT effective_amount FROM pay.pay_wallet WHERE user_id='%s'; " % userId2
connect = pymysql.connect(host=host2, port=post2, user=user2, passwd=passwd2, db=db2, charset='utf8')
cursor = connect.cursor()
cursor.execute(sq)
connect.commit() # 提交事务,改变数据的时候加这个
eff_money2 = cursor.fetchall()
cursor.close()
def query_wallet2(self):
email = self.init_data_Text.get(1.0, END)[:-1].strip()
self.f_email2()
if email:
try:
self.DB2()
self.result_data_Text.delete(1.0, END)
self.result_data_Text.insert(1.0, "电子钱包余额设置成功,")
self.result_data_Text.insert(2.0, "电子钱包余额:")
self.result_data_Text.insert(3.0, eff_money2)
self.write_log_to_Text("INFO:设置电子钱包余额success")
except:
self.result_data_Text.delete(1.0, END)
self.result_data_Text.insert(1.0, "设置电子钱包余额失败")
else:
self.write_log_to_Text("ERROR:邮箱未填写~~。")
#获取当前时间
def get_current_time(self):
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
return current_time
#日志动态打印
def write_log_to_Text(self, logmsg):
global LOG_LINE_NUM
current_time = self.get_current_time()
logmsg_in = str(current_time) +" " + str(logmsg) + "\n" #换行
logmsg_in2 = str(current_time) +" " + "**********************************\n" #换行
if LOG_LINE_NUM <= 7:
self.log_data_Text.insert(END, logmsg_in)
self.log_data_Text.insert(END, logmsg_in2)
LOG_LINE_NUM = LOG_LINE_NUM + 1
else:
self.log_data_Text.delete(1.0, 2.0)
self.log_data_Text.insert(END, logmsg_in)
self.log_data_Text.insert(END, logmsg_in2)
def gui_start():
init_window = Tk() #实例化出一个父窗口
ZMJ_PORTAL = MY_GUI(init_window)
# 设置根窗口默认属性
ZMJ_PORTAL.set_init_window()
init_window.mainloop() #父窗口进入事件循环,可以理解为保持窗口运行,否则界面不展示
gui_start()