1,使用tkinter实现计算器程序。实现效果如下:
from tkinter import *
from tkinter.ttk import *def frame(master):"""将共同的属性作为默认值, 以简化Frame创建过程"""w = Frame(master)w.pack(side=TOP, expand=YES, fill=BOTH)return wdef button(master, text, command):"""提取共同的属性作为默认值, 使Button创建过程简化"""w = Button(master, text=text, command=command, width=6)w.pack(side=LEFT, expand=YES, fill=BOTH, padx=2, pady=2)return wdef back(text):"""将text最末的字符删除并返回"""if len(text) > 0:return text[:-1]else:return textdef calc(text):"""用eval方法计算表达式字符串"""try:if (sep_flag.get() == 0):return eval(del_sep(text))else:return add_sep(str(eval(del_sep(text))))except (SyntaxError, ZeroDivisionError, NameError):return 'Error'def add_sep(text):"""向参数传入的数字串中添加千位分隔符这里考虑了三种情况: 无整数部份, 无小数部份, 同时有整数和小数部份由于字符串是不可改变的, 这里由字符串生成列表以便执行insert操作和extend操作, 操作完成后最由列表生成字符串返回 """dot_index = text.find('.')if dot_index > 0:text_head = text[:dot_index]text_tail = text[dot_index:]elif dot_index < 0:text_head = texttext_tail = ''else:text_head = ''text_tail = textlist_ = [char for char in text_head]length = len(list_)tmp_index = 3while length - tmp_index > 0:list_.insert(length - tmp_index, ',')tmp_index += 3list_.extend(text_tail)new_text = ''for char in list_:new_text += charreturn new_textdef del_sep(text):"""删除数字串中所有的千位分隔符"""return text.replace(',', '')# 开始界面的实现
root = Tk()
root.title("Calculator") # 添加标题main_menu = Menu() # 创建最上层主菜单# 创建Calculator菜单, 并加入到主菜单
calc_menu = Menu(main_menu, tearoff=0)
calc_menu.add_command(label='Quit', command=lambda: exit())
main_menu.add_cascade(label='Calculator', menu=calc_menu)# 创建View菜单, 并加入到主菜单
# 其中"Show Thousands Separator"菜单项是一个Checkbutton
text = StringVar()
sep_flag = IntVar()
sep_flag.set(0)
view_menu = Menu(main_menu, tearoff=0)
view_menu.add_checkbutton(label='Show Thousands Separator', variable=sep_flag,command=lambda t=text: t.set(add_sep(t.get())))
main_menu.add_cascade(label='View', menu=view_menu)root['menu'] = main_menu # 将主菜单与root绑定# 创建文本框
Entry(root, textvariable=text).pack(expand=YES, fill=BOTH, padx=2, pady=4)style = Style()
style.configure('TButton', padding=3)# 创建第一行三个按钮
fedit = frame(root)
button(fedit, 'Backspace', lambda t=text: t.set(back(t.get())))
button(fedit, 'Clear', lambda t=text: t.set(''))
button(fedit, '±', lambda t=text: t.set('-('+t.get()+')'))# 每行四个, 创建其余四行按钮
for key in ('789/', '456*', '123-', '0.=+'):fsymb = frame(root)for char in key:if char == '=':button(fsymb, char, lambda t=text: t.set(calc(t.get())))else:button(fsymb, char, lambda t=text, c=char: t.set(t.get()+c))root.mainloop()
效果图如下:
2,安装pillow和qrcode库并编写程序:生成带有图标的二维码,图标为自己设置的照片,扫描后打开某个网站。(如平顶山学院的网站http://www.pdsu.edu.cn)
cmd --- pip install qrcode
import qrcode
from PIL import Image
import os,sys
def gen_qrcode(string,path,logo=""):qr=qrcode.QRCode(version=2,error_correction=qrcode.constants.ERROR_CORRECT_H,box_size=8,border=1)qr.add_data(string)qr.make(fit = True)img = qr.make_image()img = img.convert("RGBA")if logo and os.path.exists(logo):try:icon = Image.open(logo)img_w,img_h = img.sizeexcept Exception as e:print(e)sys.exit(1)factor = 4;size_w = int(img_w/factor)size_h = int(img_h/factor)icon_w,icon_h=icon.sizeif icon_w > size_w:icon_w = size_wif icon_h > size_h:icon_h = size_hicon = icon.resize((icon_w,icon_h),Image.ANTIALIAS)w = int((img_w - icon_w)/2)h = int((img_h - icon_h)/2)icon = icon.convert("RGBA")img.paste(icon,(w,h),icon)img.save(path)#调用系统命令打开图片os.system("start %s" %path)if __name__ == "__main__":info = "http://www.pdsu.edu.cn"pic_path = "yanyu.png" #必须生成png格式 这里是生成的二维码图片名称icon_path = "G:\TIM\图片\yy.jpg" #可以是jpg,也可以是png 这里是中间图片的路径gen_qrcode(info,pic_path,icon_path)
效果图如下:
3,使用tkinter实现抽奖式提问程序。给出人抽奖人员名单,[‘张三’, ‘李四’, ‘王五’, ‘赵六’, ‘周七’, ‘钱八’],实现如下效果,点击开始,滚动姓名,开始抽奖,点击停,弹出中奖姓名。
import tkinter
import tkinter.messagebox
import random
import threading
import itertools
import time
root = tkinter.Tk()
#窗口标题
root.title('随机提问')
#窗口初始大小和位置
root.geometry('260x180+400+300')
#不允许改变窗口大小
root. resizable(False,False)#关闭程序时执行的函数代码,停止滚动显示学生名单
def closeWindow():root.flag = Falsetime.sleep(0.1)root.destroy()
root.protocol('WM_DELETE_WINDOW',closeWindow)
#模拟学生名单,可以加上数据库访问接口,从数据库中读取学生名单
students = ['张三','李四','王五','赵六','周七','钱八']
#变量,用来控制是否滚动显示学生名单root.flag = False
def switch():root.flag = True#随机打乱学生名单t = students[:]random.shuffle(t)t = itertools.cycle(t)while root.flag:#滚动显示lbFirst['text'] = lbSecond ['text']lbSecond['text'] = lbThird['text']lbThird['text'] = next(t)#数字可以修改,控制滚动速度time.sleep(0.1)def btnStartClick():#每次单击“开始”按钮启动新线程t = threading.Thread (target=switch)t.start()btnStart['state'] ='disabled'btnStop['state'] ='normal'
btnStart = tkinter.Button(root,text='开始',command=btnStartClick)
btnStart.place(x= 30,y=10,width=80,height=20)def btnStopClick():# 单击“停”按钮结束滚动显示root.flag = Falsetime.sleep(0.3)tkinter.messagebox.showinfo('恭喜','本次中奖:'+lbSecond['text'])btnStart['state'] ='norma1'btnStop['state'] ='disabled'
btnStop = tkinter.Button(root,text='停',command = btnStopClick)
btnStop['state'] ='disabled'
btnStop.place(x=150,y = 10,width =80,height = 20)# 用来滚动显示学生名单的3个Labe1组件
# 可以根据需要进行添加,但要修改上面的线程函数代码
lbFirst = tkinter.Label(root,text ='')
lbFirst.place(x=80,y = 60,width = 100,height = 20)
# 红色Label组件,表示中奖名单
lbSecond = tkinter.Label(root,text ='')
lbSecond['fg'] ='red'
lbSecond.place(x=80,y = 90,width = 100,height = 20)
lbThird =tkinter.Label(root,text = '' )
lbThird.place(x=80,y = 120, width = 100,height = 20)# 启动tkinter主程序
root.mainloop()
效果图如下: