LoginSignup
11
15

More than 5 years have passed since last update.

PythonでQRコードを生成して直接Tkinterに表示する

Last updated at Posted at 2017-11-17

PythonでQRコードを生成して直接Tkinterに表示する。

ファイルに保存せずに直接表示するには、PIL.ImageTk.PhotoImageが鍵でした。
ただし、Tkの初期化終了後じゃないと実行できないので注意。

pip install pillow qrcode colorama
#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import tkinter as tk
import PIL.ImageTk
import qrcode #qrcodeを起動

msg = "Hello World"
w=800
h=500

def makeQR(s):
    qr = qrcode.QRCode(
        version=None, #QRコードの大きさ(バージョン)。Noneで自動設定(1~22)。数値指定しても必要なら自動で大きくなる
        error_correction=qrcode.constants.ERROR_CORRECT_M, #誤り訂正レベルL,M,Q,H
        box_size=3, #サイズを何倍にするか。1ならdot-by-dot(px)
        border=8,#認識用余白(最低4)
    )
    qr.add_data(s)
    qr.make(fit=True)
    return qr.make_image()

root = tk.Tk()
canvas = tk.Canvas(root,width=w,height=h,bg='white')

f = ('FixedSys, 14')
imgtk = PIL.ImageTk.PhotoImage(makeQR(msg))

canvas.create_image(w/2,h/2,image = imgtk,anchor = tk.CENTER)
canvas.create_text(w/2,50,text = "Header",font=f)
canvas.create_text(w/2,450,text = "Footer",font=f)
canvas.pack()

root.mainloop()

image.png

以下のように書き換えると、ウィンドウサイズがぴったりになります。

imgtk = PIL.ImageTk.PhotoImage(makeQR(msg))
canvas = tk.Canvas(root,width=imgtk.width(),height=imgtk.height(),bg='white')
canvas.create_image(0,0,image = imgtk,anchor = tk.NW)
canvas.pack()

image.png

参考

Pythonの「qrcode」を使ってQRコードを生成する
qrcode 5.3
PythonのTkinterを使ってみる
【Python】Tkinterのcanvasを使ってみる
Python/Tkinter プログラミング講座 イメージとファイルの選択
Tkinter (Canvas)の内容をPILでキャプチャ

11
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
15