**
import re
import tkinter
import tkinter.messagebox
root = tkinter.Tk()
#设置窗口大小和位置
root.geometry('300x270+400+100')
#不允许改变窗口大小
root.resizable(False, False)
#设置窗口标题
root.title('简易计算器')
#放置用来显示信息的文本框,并设置为只读
contentVar = tkinter.StringVar(root, '')
contentEntry = tkinter.Entry(root, textvariable=contentVar)
contentEntry['state'] = 'readonly'
contentEntry.place(x=10, y=10, width=280, height=20)
#按钮通用代码,参数btn表示按钮的是哪个按钮
def buttonClick(btn):
content = contentVar.get()
#如果已有内容是以小数点开头的,前面加0
if content.startswith('.'):
content = '0' + content
#根据不同按钮做出相应的处理
if btn in '0123456789':
content += btn
elif btn == '.':
#如果最后一个运算数中已经有小数点,就提示错误
lastPart = re.split(r'\+|-|\*|/]', content)[-1]
if '.' in lastPart:
tkinter.messagebox.showerror('错误', '小数点太多了')
return
else:
content += btn
elif btn == 'C':
#清除整个表达式
content = ''
elif btn == '=':
try:
#对输入的表达式求值
content = str(eval(content))
except:
tkinter.messagebox.showerror('错误', '表达式错误')
return
elif btn in operators:
if content.endswith(operators):
tkinter.messagebox.showerror('错误',
'不允许存在连续运算符')
return
content += btn
elif btn == 'Sqrt':
n = content.split('.')
if all(map(lambda x: x.isdigit(), n)):
content = eval(content) ** 0.5
else:
tkinter.messagebox.showerror('错误', '表达式错误')
return
contentVar.set(content)
#放置清除按钮和等号按钮
btnClear = tkinter.Button(root,
text='Clear',
command=lambda:buttonClick('C'))
btnClear.place(x=40, y=40, width=80, height=20)
btnCompute = tkinter.Button(root,
text='=',
command=lambda:buttonClick('='))
btnCompute.place(x=170, y=40, width=80, height=20)
#放置10个数字、小数点和计算平方根的按钮
digits = list('0123456789.') + ['Sqrt']
index = 0
for row in range(4):
for col in range(3):
d = digits[index]
index += 1
btnDigit = tkinter.Button(root,
text=d,
command=lambda x=d:buttonClick(x))
btnDigit.place(x=20+col*70,
y=80+row*50,
width=50,
height=20)
#放置运算符按钮
operators = ('+', '-', '*', '/', '**', '//')
for index, operator in enumerate(operators):
btnOperator = tkinter.Button(root,
text=operator,
command=lambda x=operator:buttonClick(x))
btnOperator.place(x=230, y=80+index*30, width=50, height=20)
root.mainloop()
import qrcode
from PIL import Image
import os, sys
def gen_qrcode(string, path, logo=""):
"""
生成中间带logo的二维码
需要安装qrcode, PIL库
@参数 string: 二维码字符串
@参数 path: 生成的二维码保存路径
@参数 logo: logo文件路径
@return: None
"""
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.size
except 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.size
if icon_w > size_w:
icon_w = size_w
if icon_h > size_h:
icon_h = size_h
icon = 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 = "https://www.runoob.com"
pic_path = "qr.png"
icon_path = "F:\课件\图片\python\cainiao.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 = False
time.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 = False
time.sleep(0.3)
tkinter.messagebox.showinfo('恭喜',
'本次中奖:'+lbSecond['text'])
btnStart['state'] = 'normal'
btnStop['state'] = 'disabled'
btnStop = tkinter.Button(root,
text='停',
command=btnStopClick)
btnStop['state'] = 'disabled'
btnStop.place(x=150, y=10, width=80, height=20)
#用来滚动显示学生名单的3个Label组件
#可以根据需要进行添加,但要修改上面的线程函数代码
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()