top
おさだのホームページ

programs
サイト制作等で使用しているプログラムと、これまで作ってきたtkinterアプリ

サイト制作に使用しているプログラム

○ 新たなHTMLファイルの作成(雛形の作成)【Python】
copy
make_html.py
展開
折り畳む
#! /usr/local/bin/env python3
#! encode : -*- utf-8 -*-
#% 新たなhtmlページの生成

import os
import pprint
import time

MASTER_PATH = '/Users/osadamasashi/Desktop/ossa2019.stars.ne.jp'
PROFILE_PATH = 'programs/html_profile.txt'
os.chdir(MASTER_PATH)


#### 愉快な関数たち

dir_path = lambda x : '' if x == '' else '../'*dir_count(x)
dir_count = lambda x : 0 if x == '' else len(x.split('/'))
slash = lambda x : '' if x == '' else '/'

def tab_where(x:str = '3') -> str:
    x = '3' if x == '' else x
    re = ['' for i in range(4)]
    re[int(x)] = ' id="now"'
    return re

def tab_where_path(x:str, d_path:str) -> list:
    x = '3' if x == '' else x
    dir_depth = dir_count(d_path)
    re = ['../'*dir_depth for i in range(4)]
    re[int(x)] = '../'*(dir_depth-1)
    result = [re, re[int(x)], int(x)]
    return result

with open(PROFILE_PATH, 'r') as f: profile_input = f.read().split('\n')
profile_arrange = []
for p in range(len(profile_input)):
    if(len(profile_input[p]) == 0):
        profile_arrange.append('')
    elif not(profile_input[p][0] == '#'):
        profile_arrange.append(profile_input[p])


#### 付加する変数たち

KEY_LIST = ['directory', 'file_name', 'title', 'tab_now', 'og:title', 'og:description', 'og:site_name', 'og:type', 'page title', 'caption', 'insert preset', 'reset']
PROFILE = dict(zip(KEY_LIST, profile_arrange))
pprint.pprint(PROFILE)

SRC_PATH = dir_path(PROFILE['directory'])
FILE_NAME = 'NoneName_'+str(time.time()) if PROFILE['file_name'] == '' else PROFILE['file_name']
FILE_PATH = PROFILE['directory']+slash(PROFILE['directory'])+FILE_NAME+'.html'
OG_SITE_NAME = PROFILE['og:title'] if PROFILE['og:site_name'] == '' else PROFILE['og:site_name']
OG_TYPE = 'blog' if PROFILE['og:type'] == '' else PROFILE['og:type']
TAB_NOW = tab_where(PROFILE['tab_now'])
TAB_NOW_ = tab_where_path(PROFILE['tab_now'], PROFILE['directory'])
TAB_NOW_PATH = TAB_NOW_[0]
TAB_LIST = ['index', 'apps', 'Remember/Remember', 'blog']
TAB_NOW_CHAR = TAB_NOW_[1]+TAB_LIST[TAB_NOW_[2]]
TAB_LIST_JUMP = ['トップ', 'アプリ', '備忘録', 'にっき']
TAB_NOW_CHAR_JUMP = TAB_LIST_JUMP[TAB_NOW_[2]]


#### htmlソース

head = """\
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="%spic/o.ico">
    <link rel="shortcut icon" href="%spic/o.ico">
    <link rel="apple-touch-icon-precomposed" href="%spic/o.png">
    <!-- pc版css -->
    <link rel="stylesheet" href="%scss/mainContent.css" media="screen and (min-width:600px)">
    <link rel="stylesheet" href="%scss/sidebar.css" media="screen and (min-width:600px)">
    <link rel="stylesheet" href="%scss/pointerEffect.css" media="screen and (min-width:600px)">
    <!-- モバイル版css -->
    <link rel="stylesheet" href="%scss/sidebar_mobile.css" media="screen and (max-width:599px)">
    <link rel="stylesheet" href="%scss/mainContent_mobile.css" media="screen and (max-width:599px)">
    <link rel="stylesheet" href="%scss/pointerEffect_mobile.css" media="screen and (max-width:599px)">
    <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'>
    <meta property="og:title" content="%s">
    <meta property="og:description" content="%s">
    <meta property="og:site_name" content="%s">
    <meta property="og:type" content="%s">
    <meta property="og:url" content="https://ossa2019.stars.ne.jp/%s">
    <title>%s</title>
</head>
<body>
    <div class="sidebar">
        <div class="logo_content">
            <div class="logo">
                <!-- <i class='bx bxl-python'></i> -->
                <img src="%spic/o_alpha.PNG">
                <div class="name" id="jp_font">
                    おさだのホームページ
                </div>
            </div>
            <i class='bx bx-menu' id="open_btn"></i>
            <i class='bx bx-x' id="close_btn"></i>
        </div>
        <ul class="page_list">
            <!-- search -->
            <li>
                <i class='bx bx-search'></i>
                <input type="text" placeholder="サイト内検索..." id="search-key">
                <i class='bx bx-right-arrow-circle' id="search_btn" onclick="jump()"></i>
            </li>
            <!-- home -->
            <li%s>
                <a href="%sindex.html">
                    <i class='bx bx-home'></i>
                    <span class="link_name">home</span>
                </a>
                <span class="popup_text">home</span>
            </li>
            <!-- note -->
            <li%s>
                <a href="%sblog.html">
                    <i class='bx bx-book'></i>
                    <span class="link_name">note</span>
                </a>
                <span class="popup_text">note</span>
            </li>
            <!-- programs -->
            <li%s>
                <a href="%sapps.html">
                    <i class='bx bx-code-alt'></i>
                    <span class="link_name">programs</span>
                </a>
                <span class="popup_text">programs</span>
            </li>
            <!-- remember -->
            <li%s>
                <a href="%sRemember/Remember.html">
                    <i class='bx bx-paperclip'></i>
                    <span class="link_name">remember</span>
                </a>
                <span class="popup_text">remember</span>
            </li>
            <li>
                <!-- space -->
            </li>
            <!-- 基本情報技術者試験 -->
            <li>
                <a href="%sjouhou.html" target="_blank" rel="noopener noreferrer">
                    <i class='bx bx-radio-circle'></i>
                    <span class="link_name" id="jp_font">基本情報技術者試験の解答</span>
                </a>
                <span class="popup_text" id="jp_font">基本情報技術者試験の解答</span>
            </li>
            <!-- 文字数カウンター -->
            <li>
                <a href="%stext.html" target="_blank" rel="noopener noreferrer">
                    <i class='bx bx-radio-circle'></i>
                    <span class="link_name" id="jp_font">文字数カウンター</span>
                </a>
                <span class="popup_text" id="jp_font">文字数カウンター</span>
            </li>
            <li></li>
            <!-- secret page -->
            <li id="secret">
                <a href="%smyPage/home.html" target="_blank" rel="noopener noreferrer" id="secret_page">
                    <i class='bx bx-key'></i>
                    <span class="link_name">test page</span>
                </a>
                <span class="popup_text_secret">test page</span>
            </li>
        </ul>
        <div class="profile_content">
            <div class="profile">
                <div class="profile_details">
                    <div class="subscript">Writer</div>
                    <div class="name">
                        Osada Masashi
                        <br>
                        <a href="https://x.com/Masashi_Osada" target="_blank" rel="noopener noreferrer">
                            > twitter
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="main_content">
        <div class="tmTopBtn" id="topScroll" onclick="tmTopScroll()">
            <i class='bx bx-upvote'></i>
            <br>
            <span class="topScroll_ception">
                top
            </span>
        </div>
        <div class="text_content">
            <div class="top_title_text" id="jp_font">おさだのホームページ</div>
            <br>
            <div class="page_title" id="fade_0">
                <div class="title_text">
                    %s
                </div>
                <div class="caption_text" id="jp_font">
                    %s
                </div>
            </div>
"""%(SRC_PATH, SRC_PATH, SRC_PATH,
     SRC_PATH, SRC_PATH, SRC_PATH,
     SRC_PATH, SRC_PATH, SRC_PATH,
     PROFILE['og:title'],
     PROFILE['og:description'],
     OG_SITE_NAME,
     OG_TYPE,
     FILE_PATH,
     PROFILE['title'],
     SRC_PATH,
     TAB_NOW[0],
     TAB_NOW_PATH[0],
     TAB_NOW[1],
     TAB_NOW_PATH[1],
     TAB_NOW[2],
     TAB_NOW_PATH[2],
     TAB_NOW[3],
     TAB_NOW_PATH[3],
     SRC_PATH,
     SRC_PATH,
     SRC_PATH,
    PROFILE['page title'],
    PROFILE['caption'])

foot = """\
        </div>
    </div>
    <script src="%sjs/copy.js"></script>
    <script src="%sjs/scroll.js"></script>
    <script src="%sjs/sidebar.js"></script>
    <script src="%sjs/details.js"></script>
    <script src="%sjs/i_btn.js"></script>
    <script src="%sjs/pointerEffect.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="%sjs/fade.js"></script>
    <script src="%sjs/counter.js"></script>
    <script>
        let topBtn = document.querySelector(".tmTopBtn");
        $(window).on('load scroll', function(){
            if ($(window).scrollTop() > 200) {
                topBtn.classList.add("active");
            } else {
                topBtn.classList.remove("active");
            }
        });
    </script>
    <script src="%scount/count.php"></script>
</body>
</html>
"""%(SRC_PATH, SRC_PATH, SRC_PATH,
     SRC_PATH, SRC_PATH, SRC_PATH,
     SRC_PATH, SRC_PATH, SRC_PATH)


middle = """\
                <div class="article">
                    <br>
                    <div class="title" id="fade_1">text</div>
                    <div class="text" id="fade_2">
                        <span id="jp_font">
                            text
                        </span>
                    </div>
                </div>
"""


#### html書き込み

with open(MASTER_PATH+'/'+FILE_PATH, 'w') as f:
    f.write(head+middle+foot if PROFILE['insert preset'] == 't' else head+foot)


#### html_profile.txtをリセットする関数

def reset():
    with open('programs/html_profile.txt', 'w') as f:
        f.write("""\
## directory ( /Users/osadamasashi/Desktop/ossa2019.stars.ne.jp/ ˜˜ )

## file name ( ˜˜ .html )

## title

## tab_now ( 0:index, 1:note, 2:programs, 3:remember )
1
## og:title ( shortcut name )

## og:description ( site's introduction )

## og:site_name ( 2nd shortcut name )

## og:type
blog
## page title

## caption

## insert preset ( 't' or 'f' )
t
## reset ( 't' or 'f' )
t
#% end""")


#### 最後の出力

none_value = ''
for k in PROFILE.keys():
    if(PROFILE[k] == ''):
        none_value += f'{k}, '
if not(len(none_value) == 0):
    none_value = '\n空白の要素 : '+none_value[:len(none_value)-3]
    print(none_value)
else:
    print('\n空白の要素なし')
print(f'\n{FILE_PATH} を作成しました!\n')


#### html_profile.txtのリセット

if(__name__ == '__main__') and (PROFILE['reset'] == 't'):
    reset()

○ 作成するHTMLの設定情報【テキスト】
copy
html_profile.txt
展開
折り畳む
## directory ( /Users/osadamasashi/Desktop/ossa2019.stars.ne.jp/ ˜˜ )

## file name ( ˜˜ .html )

## title

## tab_now ( 0:index, 1:note, 2:programs, 3:remember )
1
## og:title ( shortcut name )

## og:description ( site's introduction )

## og:site_name ( 2nd shortcut name )

## og:type
blog
## page title

## caption

## insert preset ( 't' or 'f' )
t
## reset ( 't' or 'f' )
t
#% end






○ サイトマップの生成【Python】
copy
make_sitemap.py
展開
折り畳む
#! /usr/local/bin/env python3
#! encode : -*- utf-8 -*-
#% sitemapの生成(URL, priority, lastmod)


import os
import pathlib
import datetime
import pprint

os.chdir("/Users/osadamasashi/Desktop/ossa2019.stars.ne.jp")
SITE_NAME = "https://ossa2019.stars.ne.jp/"
PROFILE_PATH = "programs/sitemap_profile.txt"
OUTPUT_PATH = "sitemap.xml"
top_data = ["", ""]


#### sitemap_profileの読み込み

with open(PROFILE_PATH, "r", encoding="utf8") as f:
    input_txt = f.read().split("\n")[1:]
profile = dict()
for i in input_txt:
    if(len(i) != 0) and (i[0] != "#") and (i[0] != ":"):
        bf = i.split(":")
        bf[0] = bf[0].replace(" ", "")
        bf[1] = bf[1].replace(" ", "")
        profile[bf[0]] = bf[1]
    elif(i[0] == ":"):
        top_data[0] = i[1:]


#### sitemapの生成

result = """\
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<!-- created with Python program (made by osada https://ossa2019.stars.ne.jp) -->"""

for p in profile.keys():
    result += f"\n<url>\n <loc>{SITE_NAME}{p}.html</loc>\n <priority>{profile[p]}</priority>\n <lastmod>"
    file = pathlib.Path(p+".html")
    dt = datetime.datetime.fromtimestamp(file.stat().st_mtime)
    dt_str = dt.strftime("%Y-%m-%dT%H:%M:%S+09:00")
    if(p == "index"):
        top_data[1] = dt_str
    result += dt_str + "</lastmod>\n </url>"

result += """
<url>
  <loc>https://ossa2019.stars.ne.jp/</loc>
  <priority>%s</priority>
  <lastmod>%s</lastmod>
</url>

</urlset>
"""%(top_data[0], top_data[1])


#### 書き込み

with open(OUTPUT_PATH, "w", encoding="utf8") as f:
    f.write(result)


#### 最後の出力

pprint.pprint(profile)
print(f"\n{OUTPUT_PATH}に書き込みました。\n")

○ サイトマップに含めるページと優先度の設定【テキスト】
copy
sitemap_profile.txt
展開
折り畳む
#% file pass (https://ossa2019.stars.ne.jp/ ˜˜ .html) : priority
: 1.0
### independent pages
index : 1.0
apps : 1.0
## other site pages
jouhou : 1.0
text : 1.0
### blog pages
blog/blog : 0.5
## chromeEx
blog/chromeEx/chromeEx1 : 0.8
## other
blog/other/plot_anime : 0.8
blog/other/python3_10 : 0.8
blog/other/python_benri : 0.8
blog/other/linear_separation : 0.8
blog/other/rsa : 0.8
blog/other/font_class : 0.8
## number
blog/number/mandelblot : 0.8
blog/number/long_division : 0.8
blog/number/comp_binomial : 0.8
blog/number/complex : 0.8
blog/number/diff : 0.8
blog/number/isprime : 0.8
## meiro
blog/meiro/meiro1 : 0.5
blog/meiro/meiro2 : 0.5
blog/meiro/meiro3 : 0.5
### Remember pages
Remember/Remember : 0.5
## html
Remember/html/target : 1.0
## tkinter
Remember/tkinter/tkinter : 1.0
Remember/tkinter/tk1 : 1.0
Remember/tkinter/tk2 : 1.0
Remember/tkinter/tk3 : 1.0
Remember/tkinter/tk4 : 1.0
Remember/tkinter/tk5 : 1.0
Remember/tkinter/tk6 : 1.0
Remember/tkinter/tk7 : 1.0
Remember/tkinter/tk8 : 1.0
Remember/tkinter/tk9 : 1.0
Remember/tkinter/tk10 : 1.0
Remember/tkinter/tk11 : 1.0
#% end






○ PythonやJavaScriptのテキストを装飾付きのHTML形式に変換【Python】
copy
toHtml.py
展開
折り畳む
#! /usr/local/bin/env python3
#! encode : -*- utf-8 -*-


import tkinter as t

def func(code:str=None):
    # 通常変換
    def rep(xs):
        xs = xs.replace('&', '&amp;')
        #xs = xs.replace('\t', '&#9')
        xs = xs.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
        #xs = xs.replace('\t', '&ensp;&ensp;')
        xs = xs.replace(' ', '&emsp;')
        xs = xs.replace('<', '&lt;')
        xs = xs.replace('>', '&gt;')
        xs = xs.replace('¥', '&yen;')
        xs = xs.replace('←', '&larr;')
        xs = xs.replace('↑', '&uarr;')
        xs = xs.replace('→', '&rarr;')
        xs = xs.replace('↓', '&darr;')
        xs = xs.replace('ˆ', '&circ;')
        xs = xs.replace('˜', '&tilde;')
        xs = xs.replace('—', '&mdash;')
        xs = xs.replace('"', '&quot;')
        xs = xs.replace('\n', '<br>\n')
        return xs

    frm = inp.get(0., t.END)
    boo = [ True, True ]
    new = ''
    for i in frm:
        boo[1] = True
        if(boo[0]):
            if(i == ' '):
                new += '&nbsp;'
                boo[1] = False
            else:
                boo[0] = False
        if(i == '\n'):
            boo[0] = True
        if(boo[1]):
            new += rep(i)
    
    if(code=='py'):
        new = rep_py(new)
    elif(code=='html'):
        new = rep_html(new)
        new = rep_html_1(new)
    elif(code=='js'):
        new = rep_js(new)
    elif(code=='sp'):
        new = rep_sp(new)
    
    if(new[ len(new)-5: ] == '<br>\n'):
        new = new[ :len(new)-5 ]
    out.delete(0., t.END)
    out.insert(0., new)
    if(len(new) == 0):
        first()

def func_py(event):
    func('py')
def func_html(event):
    func('html')
def func_js(event):
    func('js')
def func_sp(event):
    func('sp')

# Python
def rep_py(xs):
    # ValueError
    xs = xs.replace('ValueError', '<span class="dec4">ValueError</span>')

    # dec0
    lis0 = ['def', 'return', 'import', 'pass', 'yield', 'lambda', 'raise', 'break', 'continue', 'with', 'while', 'from', 'match', 'case']
    for l in lis0:
        xs = xs.replace(l, '<span class="dec0">'+l+'</span>')
    xs = xs.replace('class ', '<span class="dec0">class</span> ')

    # dec1
    xs = xs.replace('elif', '<span class="dec1">el</span>if')
    xs = xs.replace('if(', '<span class="dec1">if</span>(')
    lis1 = ['else', 'try', 'except']
    lis1_space = ['if', 'for', 'in', 'is', 'as']
    for l in lis1:
        xs = xs.replace(l, '<span class="dec1">'+l+'</span>')
    for l in lis1_space:
        xs = xs.replace(l+' ', '<span class="dec1">'+l+'</span> ')

    # dec2
    xs = xs.replace('kwargs', '<span class="dec2">kw</span>args')
    lis2 = ['self', '@', 'event', 'args']
    for l in lis2:
        xs = xs.replace(l, '<span class="dec2">'+l+'</span>')

    # dec3
    lis3 = ['True', 'False', 'None']
    lis3_space = ['not', 'and', 'or']
    lis3_kakko = ['not', 'and', 'or']
    for l in lis3:
        xs = xs.replace(l, '<span class="dec3">'+l+'</span>')
    for l in lis3_space:
        xs = xs.replace(l+' ', '<span class="dec3">'+l+'</span> ')
    for l in lis3_kakko:
        xs = xs.replace(l+'(', '<span class="dec3">'+l+'</span>(')

    # dec4
    lis4_underScore = ['init', 'name', 'main', 'del', 'new']
    lis4_kakko = ['print', 'range', 'type', 'super', 'replace', 'open', 'close', 'read', 'write', 'isinstance', 'len', 'chr', 'ord', 'append', 'pop', 'get',
    'int', 'float', 'str', 'byte', 'list', 'dict', 'set', 'taple', 'max', 'min', 'sum', 'abs', 'translate', 'maketrans']
    for l in lis4_underScore:
        xs = xs.replace('__'+l+'__', '<span class="dec4">__'+l+'__</span>')
    for l in lis4_kakko:
        xs = xs.replace(l+'(', '<span class="dec4">'+l+'</span>(')

    # dec5
    # なし
    
    xs = xs.replace('auth<span class="dec3">or</span>', 'author')

    return xs

# HTMl
def rep_html(xs):
    # space
    xs = xs.replace('&ensp;&ensp;&ensp;&ensp;', '&ensp;&ensp;')

    # class, span
    xs = xs.replace(' class', ' <span class="dec1">class</span>')
    xs = xs.replace('&lt;/span', '&lt;/<span class="dec0">span</span>')
    xs = xs.replace('&lt;span', '&lt;<span class="dec0">span</span>')
    
    # dec0
    lis0 = ['html', 'body', 'head', 'meta', '!DOCTYPE html', 'link', 'title', 'div', 'p1', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p', 'p0', 'a', 'section', 'br', 'hr', 'script',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'h10', 'details', 'summary', 'form', 'table', 'tr', 'td', 'input', 'textarea', 'img', 'select', 'label', 'area', 'button', 'frameset', 'main']
    for l in lis0:
        xs = xs.replace('&lt;'+l, '&lt;<span class="dec0">'+l+'</span>')
        xs = xs.replace('&lt;/'+l, '&lt;/<span class="dec0">'+l+'</span>')
    # dec1
    lis1 = ['lang', 'charset', 'name', 'content', 'rel', 'href', 'media', 'property', 'id', 'style', 'src', 'action', 'type', 'value', 'size', 'checked', 'target', 'width', 'height',
    'onclick', 'ondbclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onkeypress', 'onkeyup', 'onkeydown', 'onload', 'onunload', 'onfocus', 'onblur', 'onsubmit', 'onreset', 'onselect', 'onchange', 'align', 'border']
    for l in lis1:
        xs = xs.replace(' '+l, ' <span class="dec1">'+l+'</span>')
    # dec2
    # なし

    # dec3
    # rep_html_1()
    
    # dec4
    # なし

    # dec5
    lis5 = ['altername', 'canonial', 'author', 'bookmark', 'icon', 'shortcut icon', 'stylesheet', 'og:title', 'og:description', 'og:site_name', 'og:type', 'og:url', 'apple-touch-icon-precomposed', 'UTF-8', 'SHIFT-JIS', 'viewport', 'ja', 'en']
    for l in lis5:
        xs = xs.replace('\''+l+'\'', '\'<span class="dec5">'+l+'</span>\'')
        xs = xs.replace('&quot;'+l+'&quot;', '&quot;<span class="dec5">'+l+'</span>&quot;')

    return xs

# HTML 特殊文字
def rep_html_1(xs):
    # dec3
    lis3 = ['ensp', 'lt', 'gt', 'emsp', 'amp', '#9', 'yen', 'larr', 'uarr', 'rarr', 'darr', 'circ', 'tilde', 'mdash', 'quot']
    for l in lis3:
        xs = xs.replace('&amp;'+l+';', '<span class="dec3">&amp;'+l+';</span>')
    
    return xs

# JavaScript
def rep_js(xs):
    # dec0
    lis0 = ['function', 'let', 'const', 'var']
    for l in lis0:
        xs = xs.replace(l, '<span class="dec0">'+l+'</span>')
    # dec1
    lis1 = ['for', 'else', 'try', 'catch', 'return', 'break', 'continue']
    for l in lis1:
        xs = xs.replace(l, '<span class="dec1">'+l+'</span>')
    xs = xs.replace('elif', '<span class="dec1">el</span>if')
    xs = xs.replace('if(', '<span class="dec1">if</span>(')
    xs = xs.replace('if (', '<span class="dec1">if</span> (')
    # dec2
    xs = xs.replace('\'use strict\';', '<span class="dec2">\'use strict\';</span>')
    xs = xs.replace('&quot;use strict&quot;;', '<span class="dec2">&quot;use strict&quot;;</span>')
    # dec3
    lis3 = ['true', 'false', 'none', 'String', 'Boolean', 'int', 'float', 'any', 'Number']
    for l in lis3:
        xs = xs.replace(l, '<span class="dec3">'+l+'</span>')
    # dec4
    lis4 = ['window', 'console', 'log', 'confirm', 'alert', 'document', 'body', 'documentElement', 'scrollLeft', 'scrollRight', 'scrollTop', 'scrollBottom', 'location', 'href', 'Math', 'round'
    ,'getElementById', 'getElementsByName', 'getElementsByClassName', 'event', 'innerHTML', 'value', 'onsubmit', 'onclick', 'onkeyup', 'onkeydown', 'replace', 'length', 'textContent', 'checked',
    'fromCharCode', 'charCodeAt', 'keyup', 'click', 'submit', 'keydown', 'execCommand', 'addEventListener', 'select', 'innerText']
    for l in lis4:
        xs = xs.replace(l, '<span class="dec4">'+l+'</span>')
    xs = xs.replace('pr<span class="dec4">event</span>Default', '<span class="dec4">preventDefault</span>')
    # dec5

    return xs

#特殊変換
def rep_sp(xs):
    #dec2
    lis2 = ['*']
    for l in lis2:
        xs = xs.replace(l, '<span class="dec2">'+l+'</span>')
    #dec6
    lis6 = ['&gt;&gt;', '$', '%']
    for l in lis6:
        xs = xs.replace(l, '<span class="dec6">'+l+'</span>')
    return xs

def first():
    out.insert(0., '←左画面にHtmlに変換したい文章を入力')

def main():
    global app, inp, out
    
    app = t.Tk()
    app.geometry('1300x625')
    app.title('Text to Html 変換アプリ')
    app.resizable(width=False, height=False)
    
    inp = t.Text(app, background='#f0f0e0', font=('Arial',12))
    inp.place(x=0, y=0, width=500, height=600)
    out = t.Text(app, background='#d0d0f8', font=('Arial',12))
    out.place(x=500, y=0, width=800, height=600)

    but = t.Button(text=u'通常変換', background='#ffaaaa')
    but.place(x=5, y=600, width=70, height=20)
    but.bind('<Button-1>', func)
    but_py = t.Button(text=u'Python', background='#ffffff')
    but_py.place(x=75, y=600, width=70, height=20)
    but_py.bind('<Button-1>', func_py)
    but_html = t.Button(text=u'HTML', background='#ffffff')
    but_html.place(x=145, y=600, width=70, height=20)
    but_html.bind('<Button-1>', func_html)
    but_js = t.Button(text=u'JavaScript', background='#ffffff')
    but_js.place(x=215, y=600, width=70, height=20)
    but_js.bind('<Button-1>', func_js)
    but_sp = t.Button(text=u'特殊変換', background='#ffffff')
    but_sp.place(x=285, y=600, width=70, height=20)
    but_sp.bind('<Button-1>', func_sp)
    but['background'] = '#ffffff'
    but_py['background'] = '#ffffff'
    but_html['background'] = '#ffffff'
    but_js['background'] = '#ffffff'
    but_sp['background'] = '#ffffff'
    app.bind('<Key-v>', func)
    
    first()
    
    app.mainloop()

if(__name__ == '__main__'):
    main()






このサイトのソースコード
(ちょくちょく変更しているので現在使用しているものとは異なるかもしれません)



○ サイト内検索の結果表示【HTML, JavaScript/jQuery】
copy
result.html
展開
折り畳む
    ...
    前略

                    <div class="title" id="search_result">検索結果</div>
                </span>
                <span id="fade_3">
                    <div id="result"></div>
                </span>
            </div>
        </div>
    </div>
    <script
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous"></script>
    <script>
        
        let v = new URLSearchParams(window.location.search);
        let site_name;
        let site_url;
        let site_info;
        let match_result = 0;
        v = v.get('search-key');
        document.getElementById("search_result").textContent ="「" + v + "」の検索結果"

        if(v == ""){
            document.getElementById("result").innerHTML = '<br>\
            <div class="window" id="fade_4">\
                    <div class="window_btn">\
                        <div class="red"></div>\
                        <div class="yellow"></div>\
                        <div class="green"></div>\
                    </div>\
                    <div class="window_title">エラー</div>\
                    <div class="window_content">\
                        <div class="window_content_buf"></div>\
                        <div class="window_text" id="jp_font">\
                            検索欄に文字を入力してください。\
                        </div>\
                    </div>\
                </div>';
        }
        else{
            const urlLists = [
            "apps.html",
            "appError.html",
            "jouhou.html",
            "text.html",
            "blog\\chromeEx\\chromeEx1.html",
            "blog\\other\\plot_anime.html",
            "blog\\other\\python3_10.html",
            "blog\\other\\python_benri.html",
            "blog\\other\\linear_separation.html",
            "blog\\other\\rsa.html",
            "blog\\other\\font_class.html",
            "blog\\number\\mandelblot.html",
            "blog\\number\\long_division.html",
            "blog\\number\\comp_binomial.html",
            "blog\\number\\complex.html",
            "blog\\number\\diff.html",
            "blog\\number\\isprime.html",
            "blog\\meiro\\meiro1.html",
            "blog\\meiro\\meiro2.html",
            "blog\\meiro\\meiro3.html",
            "Remember\\html\\target.html",
            "Remember\\tkinter\\tkinter.html",
            "Remember\\tkinter\\tk1.html",
            "Remember\\tkinter\\tk2.html",
            "Remember\\tkinter\\tk3.html",
            "Remember\\tkinter\\tk4.html",
            "Remember\\tkinter\\tk5.html",
            "Remember\\tkinter\\tk6.html",
            "Remember\\tkinter\\tk7.html",
            "Remember\\tkinter\\tk8.html",
            "Remember\\tkinter\\tk9.html",
            "Remember\\tkinter\\tk10.html",
            "Remember\\tkinter\\tk11.html"
            ];

            $.each(urlLists, function(i){
                $.ajax({
                    url : urlLists[i],
                    dataType: 'html',
                    success: function(data){
                        if( $(data).text().indexOf(v) !== -1){
                            match_result = 1;
                            site_name = $(data).find("p").text()
                            if(site_name.length == 0){
                                site_name = $(data).find(".title_text").text()
                            }
                            site_name = site_name.replace("おさだのホームページ", "");
                            site_name = site_name.replace("目次", "tkinter ");
                            site_name = site_name.replace("Pythonのソースコード.exeが入ったzipファイルエラーが出るときの対処法", "自作アプリのページ")
                            site_name = site_name.replace("ホームに戻る   書いた文章をクリップボードにコピー", "リアルタイムで文字数を数えるだけのページ")
                            site_name = site_name.replace("バージョン情報読み込み失敗", "")
                            site_name = site_name.replace("サイト制作に使っているプログラムこのサイトのソースコードtkinterを利用したアプリエラーが出るときの対処法", "倉庫のページ");
                            site_url = urlLists[i];
                            site_info = $(data).find(".text").text();
                            if(site_info.length == 0){
                                site_info = $(data).find("div").text()
                            }
                            site_info = site_info.replace("おさだのホームページ", "");
                            site_info = site_info.replace("▲top", "");
                            site_info = site_info.replace("ホーム", "");
                            site_info = site_info.replace("アプリ", "");
                            site_info = site_info.replace("備忘録", "");
                            site_info = site_info.replace("にっき", "");
                            site_info = site_info.replace("倉 庫", "");
                            site_info = site_info.replace("javascript読み込み失敗一部の追加機能、または全ての機能が利用できない可能性があります。ページを更新しても治らない場合はブラウザを変えてみてください。", "基本情報技術者試験の試験の解答照会のページ");
                            site_info = site_info.slice(0, 500);
                            $('\
                            <div class="link_content">\
                                <div class="link">\
                                    <a href="' + site_url + '">\
                                    ' + site_name + '\
                                    </a><br><div class="article_caption" id="jp_font">\
                                    ' + site_info + '\
                                </div>\
                                <br>\
                            </div>').appendTo("#result");
                        }
                    },
                    error: function(data){
                        console.log("error");
                    }
                });
            });
        }

    後略
    ...

○ result.htmlへのデータの受け渡し【JavaScript】
copy
i_btn.js
展開
折り畳む
"use strict";

function jump(){
    location.href="https://ossa2019.stars.ne.jp/result.html?search-key=" + document.getElementById("search-key").value;
};






○ ページの遅延表示【JavaScript】
copy
fade.js
展開
折り畳む
"use strict";

function fade(target, start, end){
    $(target).append(
        "<style>" + target + "{display:none;}"
    );
    $(window).on("load", function() {
        $(target).delay(start).fadeIn(end);
    });
}

const mono = 150;

fade("#fade_0", 0, 500);
fade("#fade_1", mono, 500);
fade("#fade_2", mono*2, 500);
fade("#fade_3", mono*3, 500);
fade("#fade_4", mono*4, 500);
fade("#fade_5", mono*5, 500);
fade("#fade_6", mono*6, 500);
fade("#fade_7", mono*7, 500);
fade("#fade_8", mono*8, 500);
fade("#fade_9", mono*9, 500);
fade("#fade_10", mono*10, 500);
fade("#fade_11", mono*11, 500);
fade("#fade_12", mono*12, 500);
fade("#fade_13", mono*13, 500);
fade("#fade_14", mono*14, 500);
fade("#fade_15", mono*15, 500);
fade("#fade_16", mono*16, 500);
fade("#fade_17", mono*17, 500);
fade("#fade_18", mono*18, 500);
fade("#fade_19", mono*19, 500);
fade("#fade_20", mono*20, 500);
fade("#fade_21", mono*21, 500);
fade("#fade_22", mono*22, 500);
fade("#fade_23", mono*23, 500);
fade("#fade_24", mono*24, 500);
fade("#fade_25", mono*25, 500);
fade("#fade_26", mono*26, 500);
fade("#fade_27", mono*27, 500);
fade("#fade_28", mono*28, 500);
fade("#fade_29", mono*29, 500);
fade("#fade_default", 500, "slow");






○ ページ表示回数のカウント【PHP】
copy
count.php
展開
折り畳む
<?php

function set_count($file_name){
    $handle = fopen($file_name, 'r');
    $count = (int)fread($handle, 20) + 1;
    $handle = fopen($file_name, 'w');
    fwrite($handle, $count);
    fclose($handle);
    return $count;
}

function file_append($path, $data){
    if (!$fp = fopen($path, 'ab')) {return false;}
    flock($fp, LOCK_EX);
    $result = fwrite($fp, $data);
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $result;
}

$a = set_count('countBuffer.txt');
$f = 'count.txt';
file_append($f, "\n");
file_append($f, $a);
file_append($f, "\t");
file_append($f, $_SERVER['REMOTE_ADDR']);

?>

○ 表示回数カウンター(ホームの上部にある紫色のやつ)の表示【JavaScript】
copy
counter.js
展開
折り畳む
"use strict";

fetch("../count/countBuffer.txt")
  .then(res=>res.text())
  .then(text=>document.getElementById("counter").textContent=text);






○ サイト上部までのスクロールボタン【JavaScript】
copy
scroll.js
展開
折り畳む
"use strict";

// 画面上までスクロール
let vGoTop = {};
function tmTopScroll(){

    vGoTop["coef"] = 50;
    vGoTop["cnt"] = 0;

    let startX = document.body.scrollLeft || document.documentElement.scrollLeft;
    let startY = document.body.scrollTop || document.documentElement.scrollTop;

    let moveSplitCnt = 0;
    for(let i = 1; i <= vGoTop["coef"]; i++) {
        moveSplitCnt += i * i;
    }
    vGoTop["unitH"] = startY / ( moveSplitCnt * 2 );

    vGoTop["nextX"] = startX;
    vGoTop["nextY"] = startY;

    tmTopScrollLoop();
}
function tmTopScrollLoop(){
    vGoTop["cnt"]++;

    let Coef = 0;
    if(vGoTop["cnt"] <= vGoTop["coef"]){
        Coef = vGoTop["cnt"];
    }else{
        Coef = ((vGoTop["coef"] * 2) + 1) - vGoTop["cnt"];
    }
    vGoTop["nextY"] = vGoTop["nextY"] - Math.round( vGoTop["unitH"] * ( Coef * Coef) );
    if((vGoTop["cnt"] >= (vGoTop["coef"] * 2))||(vGoTop["nextY"] <= 0)){
        vGoTop["nextY"] = 0;
    }

    window.scrollTo(vGoTop["nextX"], vGoTop["nextY"]);

    if(vGoTop["nextY"] <= 0){
        clearTimeout(vGoTop["timer"]);
    }else{
        vGoTop["timer"] = setTimeout("tmTopScrollLoop()",10);
    }
}






○ サイドバーの展開・格納【JavaScript】
copy
sidebar.js
展開
折り畳む
"use strict";

let sidebar = document.querySelector(".sidebar");
let mainContent = document.querySelector(".main_content");

// サイドバーの展開・格納
function sidebar_activate(key) {
    key.addEventListener("click", function() {
        if(sidebar.classList.contains("active")){
            sidebar.classList.remove("active");
            mainContent.classList.remove("active");
        }else{
            sidebar.classList.add("active");
            mainContent.classList.add("active");
        };
    });
}

let openBtn = document.getElementById("open_btn");
let closeBtn = document.getElementById("close_btn");
let searchBtn = document.querySelector(".bx-search");

sidebar_activate(openBtn);
sidebar_activate(closeBtn);
sidebar_activate(searchBtn);


○ サイドバーのスタイルシート【CSS】
copy
sidebar.css
展開
折り畳む
body{
    position: relative;
    min-height: 100vh;
    width: 100%;
}

/* サイドバー width: 300px; */
.sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 78px;
    background: #11101d;
    padding: 6px 14px;
    transition: all 0.5s ease;
    z-index: 2;
}
.sidebar.active{
    width: 300px;
}

/* サイドバー > ロゴ、ハンバーガー */
.sidebar .logo_content .logo{
    color: #fff;
    display: flex;
    height: 50px;
    width: 100%;
    align-items: center;
    opacity: 0;
    pointer-events: none;
    transition: all 0.4s ease;
    padding-left: 14px;
}
.sidebar.active .logo_content .logo{
    opacity: 1;
    pointer-events: none;
}
.sidebar .logo_content .logo img{
    height: 20px;
    width: 20px;
    object-fit: cover;
    border-radius: 12px;
    margin-right: 10px;
}
.sidebar .logo_content .logo .logo_name{
    font-size: 20px;
    font-weight: 400;
}
.sidebar #open_btn{
    position: absolute;
    color: #fff;
    left: 50%;
    top: 6px;
    font-size: 20px;
    height: 50px;
    width: 50px;
    text-align: center;
    line-height: 50px;
    transform: translateX(-50%);
    transition: all 0.4s ease;
    cursor: pointer;
    cursor: hand;
    opacity: 1;
}
.sidebar.active #open_btn{
    opacity: 0;
    left: 70%;
}
.sidebar #open_btn:hover{
    color: #9ff;
    transform: scale(1.5) translateX(-17px) rotateZ(180deg);
}
.sidebar #close_btn{
    position: absolute;
    color: #fff;
    left: -20%;
    top: 6px;
    font-size: 20px;
    height: 50px;
    width: 50px;
    text-align: center;
    line-height: 50px;
    transform: translateX(-50%);
    transition: all 0.4s ease;
    cursor: pointer;
    cursor: hand;
    opacity: 0;
}
.sidebar.active #close_btn{
    opacity: 1;
    left: 88%;
}
.sidebar #close_btn:hover{
    transform: scale(1.5) translateX(-17px) rotate(180deg);
    color: #f88;
}

/* サイドバー > リンク */
.sidebar ul{
    margin-top: 20px;
}
.sidebar ul li{
    position: relative;
    height: 50px;
    width: 100%;
    list-style: none;
    line-height: 50px;
}
.sidebar ul li input{
    position: absolute;
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    border-radius: 12px;
    outline: none;
    border: none;
    background: #2a2845;
    padding: 0 0px;
    font-size: 18px;
    color: #fff;
    font-family: 'Noto Sans JP', sans-serif;
    font-weight: 100;
    opacity: 0;
}
.sidebar.active ul li input{
    opacity: 1;
    padding: 0 20%;
}
.sidebar ul li .bx-search{
    position: absolute;
    z-index: 1;
    color: #fff;
    font-size: 20px;
    transition: all 0.5s ease;
    background: #2a2845;
    cursor: pointer;
    cursor: hand;
}
.sidebar ul li .bx-search:hover{
    background: #fff;
    color: #11101d;
}
.sidebar ul li .bx-right-arrow-circle{
    position: absolute;
    z-index: 1;
    color: #fff;
    font-size: 30px;
    transition: all 0.5s ease;
    opacity: 0;
    left: 218px;
    padding: 0 12px;
    cursor: pointer;
    cursor: hand;
}
.sidebar.active ul li .bx-right-arrow-circle{
    opacity: 1;
}
.sidebar ul li i#search_btn:hover{
    background: #fff;
    color: #f03030;
    transform: scale(1.2);
}
.sidebar ul li a{
    color: #fff;
    display: flex;
    align-items: center;
    text-decoration: none;
    transition: all 0.4s ease;
    border-radius: 12px;
}
.sidebar ul li a:hover{
    color: #11101d;
    background: #fff;
}
.sidebar ul li#now a{
    color: #fff;
    display: flex;
    align-items: center;
    transition: all 0.4s ease;
    border-radius: 12px;
}
.sidebar ul li#now a i{
    text-decoration: underline #f08080;
}
.sidebar ul li#now a:hover{
    color: #11101d;
    background: #fff;
}
.sidebar ul li#now a:hover i{
    transform: none;
}
.sidebar ul li#secret a i{
    transition: all 0.6s ease;
}
.sidebar ul li#secret a:hover i{
    transform: rotateZ(-360deg);
}
.sidebar ul li i{
    height: 50px;
    min-width: 30px;
    border-radius: 12px;
    line-height: 50px;
    list-style: none;
    text-align: center;
    padding: 0 15px;
    font-size: 20px;
}
.sidebar .link_name{
    opacity: 0;
    pointer-events: none;
    transition: all 0.2s ease;
    height: 50px;
    /* padding-left: 10px; */
}
.sidebar.active .link_name{
    opacity: 1;
    pointer-events: auto;
}
.sidebar ul li #secret_page{
    color: #fff;
}
.sidebar ul li #secret_page:hover{
    color: #000;
    background: #aaa;
}
.sidebar ul li .popup_text{
    position: absolute;
    left: 185px;
    top: -20%;
    transform: translateX(-50%);
    border-radius: 6px;
    height: 35px;
    width: 220px;
    background: #fff;
    line-height: 35px;
    text-align: center;
    box-shadow: 0 5px 10px #00000040;
    transition: 0s;
    opacity: 0;
    pointer-events: none;
    display: block;
    z-index: 2;
}
.sidebar.active ul li .popup_text{
    display: none;
}
.sidebar ul li .popup_text_secret{
    position: absolute;
    left: 185px;
    top: -20%;
    transform: translateX(-50%);
    border-radius: 6px;
    height: 35px;
    width: 220px;
    color: #11101d;
    background: #ccc;
    line-height: 35px;
    text-align: center;
    box-shadow: 0 5px 10px #00000040;
    transition: 0s;
    opacity: 0;
    pointer-events: none;
    z-index: 2;
}
.sidebar.active ul li .popup_text_secret{
    display: none;
}
.sidebar ul li:hover .popup_text{
    transition: all 0.5s ease;
    opacity: 1;
    top: 15%;
    z-index: 2;
}
.sidebar ul li:hover .popup_text_secret{
    transition: all 0.5s ease;
    opacity: 1;
    top: 15%;
}

/* サイドバー > 左下プロフィール */
.sidebar .profile_content{
    position: absolute;
    color: #fff;
    bottom: 0;
    left: 0;
    opacity: 0;
    transition: all 0.4s ease;
    background-color: #333;
    width: 100%;
}
.sidebar.active .profile_content{
    opacity: 1;
}
.sidebar .profile_content .profile{
    position: relative;
    padding: 10px 6px;
    height: 60px;
}
.sidebar .profile_content .profile .profile_details{
    display: flex;
    align-items: center;
}
.sidebar .profile_content .profile .profile_details .subscript{
    padding-right: 20px;
    padding-left: 10px;
}
.sidebar .profile_content .profile .profile_details a{
    color: #2affff;
    text-decoration: none;
    border-radius: 5px;
    transition: all 0.4s ease;
}
.sidebar .profile_content .profile .profile_details a:hover{
    color: #000;
    background-color: #2affff;
    text-decoration: none;
}

/* メインコンテンツ */
.main_content{
    position: absolute;
    height: 100%;
    width: calc(100% - 78px);
    left: 78px;
    transition: all 0.5s ease;
}
.sidebar.active ˜ .main_content{
    width: calc(100% - 300px);
    left: 300px;
}

○ サイドバーのHTMLテキスト【HTML】
copy
index.html(途中抜粋)
展開
折り畳む
・・・
前略

<link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'>
<link rel="stylesheet" href="css/sidebar.css">

・・・
中略
・・・

    <div class="sidebar">
        <div class="logo_content">
            <div class="logo">
                <!-- <i class='bx bxl-python'></i> -->
                <img src="pic/o_alpha.PNG">
                <div class="name" id="jp_font">
                    おさだのホームページ
                </div>
            </div>
            <i class='bx bx-menu' id="open_btn"></i>
            <i class='bx bx-x' id="close_btn"></i>
        </div>
        <ul class="page_list">
            <!-- search -->
            <li>
                <i class='bx bx-search'></i>
                <input type="text" placeholder="サイト内検索..." id="search-key">
                <i class='bx bx-right-arrow-circle' id="search_btn" onclick="jump()"></i>
            </li>
            <!-- home -->
            <li>
                <a href="index.html">
                    <i class='bx bx-home'></i>
                    <span class="link_name">home</span>
                </a>
                <span class="popup_text">home</span>
            </li>
            <!-- note -->
            <li>
                <a href="blog/blog.html">
                    <i class='bx bx-book'></i>
                    <span class="link_name">note</span>
                </a>
                <span class="popup_text">note</span>
            </li>
            <!-- programs -->
            <li id="now">
                <a href="apps.html">
                    <i class='bx bx-code-alt'></i>
                    <span class="link_name">programs</span>
                </a>
                <span class="popup_text">programs</span>
            </li>
            <!-- remember -->
            <li>
                <a href="Remember/Remember.html">
                    <i class='bx bx-paperclip'></i>
                    <span class="link_name">remember</span>
                </a>
                <span class="popup_text">remember</span>
            </li>
            <li>
                <!-- space -->
            </li>
            <!-- 基本情報技術者試験 -->
            <li>
                <a href="jouhou.html" target="_blank" rel="noopener noreferrer">
                    <i class='bx bx-radio-circle'></i>
                    <span class="link_name" id="jp_font">基本情報技術者試験の解答</span>
                </a>
                <span class="popup_text" id="jp_font">基本情報技術者試験の解答</span>
            </li>
            <!-- 文字数カウンター -->
            <li>
                <a href="text.html" target="_blank" rel="noopener noreferrer">
                    <i class='bx bx-radio-circle'></i>
                    <span class="link_name" id="jp_font">文字数カウンター</span>
                </a>
                <span class="popup_text" id="jp_font">文字数カウンター</span>
            </li>
            <li></li>
            <!-- secret page -->
            <li id="secret">
                <a href="myPage/home.html" target="_blank" rel="noopener noreferrer" id="secret_page">
                    <i class='bx bx-key'></i>
                    <span class="link_name">test page</span>
                </a>
                <span class="popup_text_secret">test page</span>
            </li>
        </ul>
        <div class="profile_content">
            <div class="profile">
                <div class="profile_details">
                    <div class="subscript">Writer</div>
                    <div class="name">
                        Osada Masashi
                        <br>
                        <a href="https://x.com/Masashi_Osada" target="_blank" rel="noopener noreferrer">
                            > twitter
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

後略
・・・






○ クリップボードへのコピー【JavaScript】
copy
copy.js
展開
折り畳む
"use strict";

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
 
// コピーをした際のポップアップの表示、onclick="onClickCopy(コピーするセレクタ, ポップアップのセレクタ)" で実行。
async function popupText(popupId) {
    let copied = document.getElementById(popupId);
    copied.classList.add("active");
    await sleep(2000);
    copied.classList.remove("active");
}

function onClickCopy(textId, popupId){
    let target = document.getElementById(textId);
    let range = document.createRange();
    range.selectNodeContents(target);
    let selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand('copy');
    selection.removeAllRanges();

    popupText(popupId);
}





tkinterを利用したアプリ

○ PythonやJavaScriptのテキストを装飾付きのHTML形式に変換【Python】
copy
toHtml.py
展開
折り畳む
#! /usr/local/bin/env python3
#! encode : -*- utf-8 -*-


import tkinter as t

def func(code:str=None):
    # 通常変換
    def rep(xs):
        xs = xs.replace('&', '&amp;')
        #xs = xs.replace('\t', '&#9')
        xs = xs.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
        #xs = xs.replace('\t', '&ensp;&ensp;')
        xs = xs.replace(' ', '&emsp;')
        xs = xs.replace('<', '&lt;')
        xs = xs.replace('>', '&gt;')
        xs = xs.replace('¥', '&yen;')
        xs = xs.replace('←', '&larr;')
        xs = xs.replace('↑', '&uarr;')
        xs = xs.replace('→', '&rarr;')
        xs = xs.replace('↓', '&darr;')
        xs = xs.replace('ˆ', '&circ;')
        xs = xs.replace('˜', '&tilde;')
        xs = xs.replace('—', '&mdash;')
        xs = xs.replace('"', '&quot;')
        xs = xs.replace('\n', '<br>\n')
        return xs

    frm = inp.get(0., t.END)
    boo = [ True, True ]
    new = ''
    for i in frm:
        boo[1] = True
        if(boo[0]):
            if(i == ' '):
                new += '&nbsp;'
                boo[1] = False
            else:
                boo[0] = False
        if(i == '\n'):
            boo[0] = True
        if(boo[1]):
            new += rep(i)
    
    if(code=='py'):
        new = rep_py(new)
    elif(code=='html'):
        new = rep_html(new)
        new = rep_html_1(new)
    elif(code=='js'):
        new = rep_js(new)
    elif(code=='sp'):
        new = rep_sp(new)
    
    if(new[ len(new)-5: ] == '<br>\n'):
        new = new[ :len(new)-5 ]
    out.delete(0., t.END)
    out.insert(0., new)
    if(len(new) == 0):
        first()

def func_py(event):
    func('py')
def func_html(event):
    func('html')
def func_js(event):
    func('js')
def func_sp(event):
    func('sp')

# Python
def rep_py(xs):
    # ValueError
    xs = xs.replace('ValueError', '<span class="dec4">ValueError</span>')

    # dec0
    lis0 = ['def', 'return', 'import', 'pass', 'yield', 'lambda', 'raise', 'break', 'continue', 'with', 'while', 'from', 'match', 'case']
    for l in lis0:
        xs = xs.replace(l, '<span class="dec0">'+l+'</span>')
    xs = xs.replace('class ', '<span class="dec0">class</span> ')

    # dec1
    xs = xs.replace('elif', '<span class="dec1">el</span>if')
    xs = xs.replace('if(', '<span class="dec1">if</span>(')
    lis1 = ['else', 'try', 'except']
    lis1_space = ['if', 'for', 'in', 'is', 'as']
    for l in lis1:
        xs = xs.replace(l, '<span class="dec1">'+l+'</span>')
    for l in lis1_space:
        xs = xs.replace(l+' ', '<span class="dec1">'+l+'</span> ')

    # dec2
    xs = xs.replace('kwargs', '<span class="dec2">kw</span>args')
    lis2 = ['self', '@', 'event', 'args']
    for l in lis2:
        xs = xs.replace(l, '<span class="dec2">'+l+'</span>')

    # dec3
    lis3 = ['True', 'False', 'None']
    lis3_space = ['not', 'and', 'or']
    lis3_kakko = ['not', 'and', 'or']
    for l in lis3:
        xs = xs.replace(l, '<span class="dec3">'+l+'</span>')
    for l in lis3_space:
        xs = xs.replace(l+' ', '<span class="dec3">'+l+'</span> ')
    for l in lis3_kakko:
        xs = xs.replace(l+'(', '<span class="dec3">'+l+'</span>(')

    # dec4
    lis4_underScore = ['init', 'name', 'main', 'del', 'new']
    lis4_kakko = ['print', 'range', 'type', 'super', 'replace', 'open', 'close', 'read', 'write', 'isinstance', 'len', 'chr', 'ord', 'append', 'pop', 'get',
    'int', 'float', 'str', 'byte', 'list', 'dict', 'set', 'taple', 'max', 'min', 'sum', 'abs', 'translate', 'maketrans']
    for l in lis4_underScore:
        xs = xs.replace('__'+l+'__', '<span class="dec4">__'+l+'__</span>')
    for l in lis4_kakko:
        xs = xs.replace(l+'(', '<span class="dec4">'+l+'</span>(')

    # dec5
    # なし
    
    xs = xs.replace('auth<span class="dec3">or</span>', 'author')

    return xs

# HTMl
def rep_html(xs):
    # space
    xs = xs.replace('&ensp;&ensp;&ensp;&ensp;', '&ensp;&ensp;')

    # class, span
    xs = xs.replace(' class', ' <span class="dec1">class</span>')
    xs = xs.replace('&lt;/span', '&lt;/<span class="dec0">span</span>')
    xs = xs.replace('&lt;span', '&lt;<span class="dec0">span</span>')
    
    # dec0
    lis0 = ['html', 'body', 'head', 'meta', '!DOCTYPE html', 'link', 'title', 'div', 'p1', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p', 'p0', 'a', 'section', 'br', 'hr', 'script',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'h10', 'details', 'summary', 'form', 'table', 'tr', 'td', 'input', 'textarea', 'img', 'select', 'label', 'area', 'button', 'frameset', 'main']
    for l in lis0:
        xs = xs.replace('&lt;'+l, '&lt;<span class="dec0">'+l+'</span>')
        xs = xs.replace('&lt;/'+l, '&lt;/<span class="dec0">'+l+'</span>')
    # dec1
    lis1 = ['lang', 'charset', 'name', 'content', 'rel', 'href', 'media', 'property', 'id', 'style', 'src', 'action', 'type', 'value', 'size', 'checked', 'target', 'width', 'height',
    'onclick', 'ondbclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmouseout', 'onkeypress', 'onkeyup', 'onkeydown', 'onload', 'onunload', 'onfocus', 'onblur', 'onsubmit', 'onreset', 'onselect', 'onchange', 'align', 'border']
    for l in lis1:
        xs = xs.replace(' '+l, ' <span class="dec1">'+l+'</span>')
    # dec2
    # なし

    # dec3
    # rep_html_1()
    
    # dec4
    # なし

    # dec5
    lis5 = ['altername', 'canonial', 'author', 'bookmark', 'icon', 'shortcut icon', 'stylesheet', 'og:title', 'og:description', 'og:site_name', 'og:type', 'og:url', 'apple-touch-icon-precomposed', 'UTF-8', 'SHIFT-JIS', 'viewport', 'ja', 'en']
    for l in lis5:
        xs = xs.replace('\''+l+'\'', '\'<span class="dec5">'+l+'</span>\'')
        xs = xs.replace('&quot;'+l+'&quot;', '&quot;<span class="dec5">'+l+'</span>&quot;')

    return xs

# HTML 特殊文字
def rep_html_1(xs):
    # dec3
    lis3 = ['ensp', 'lt', 'gt', 'emsp', 'amp', '#9', 'yen', 'larr', 'uarr', 'rarr', 'darr', 'circ', 'tilde', 'mdash', 'quot']
    for l in lis3:
        xs = xs.replace('&amp;'+l+';', '<span class="dec3">&amp;'+l+';</span>')
    
    return xs

# JavaScript
def rep_js(xs):
    # dec0
    lis0 = ['function', 'let', 'const', 'var']
    for l in lis0:
        xs = xs.replace(l, '<span class="dec0">'+l+'</span>')
    # dec1
    lis1 = ['for', 'else', 'try', 'catch', 'return', 'break', 'continue']
    for l in lis1:
        xs = xs.replace(l, '<span class="dec1">'+l+'</span>')
    xs = xs.replace('elif', '<span class="dec1">el</span>if')
    xs = xs.replace('if(', '<span class="dec1">if</span>(')
    xs = xs.replace('if (', '<span class="dec1">if</span> (')
    # dec2
    xs = xs.replace('\'use strict\';', '<span class="dec2">\'use strict\';</span>')
    xs = xs.replace('&quot;use strict&quot;;', '<span class="dec2">&quot;use strict&quot;;</span>')
    # dec3
    lis3 = ['true', 'false', 'none', 'String', 'Boolean', 'int', 'float', 'any', 'Number']
    for l in lis3:
        xs = xs.replace(l, '<span class="dec3">'+l+'</span>')
    # dec4
    lis4 = ['window', 'console', 'log', 'confirm', 'alert', 'document', 'body', 'documentElement', 'scrollLeft', 'scrollRight', 'scrollTop', 'scrollBottom', 'location', 'href', 'Math', 'round'
    ,'getElementById', 'getElementsByName', 'getElementsByClassName', 'event', 'innerHTML', 'value', 'onsubmit', 'onclick', 'onkeyup', 'onkeydown', 'replace', 'length', 'textContent', 'checked',
    'fromCharCode', 'charCodeAt', 'keyup', 'click', 'submit', 'keydown', 'execCommand', 'addEventListener', 'select', 'innerText']
    for l in lis4:
        xs = xs.replace(l, '<span class="dec4">'+l+'</span>')
    xs = xs.replace('pr<span class="dec4">event</span>Default', '<span class="dec4">preventDefault</span>')
    # dec5

    return xs

#特殊変換
def rep_sp(xs):
    #dec2
    lis2 = ['*']
    for l in lis2:
        xs = xs.replace(l, '<span class="dec2">'+l+'</span>')
    #dec6
    lis6 = ['&gt;&gt;', '$', '%']
    for l in lis6:
        xs = xs.replace(l, '<span class="dec6">'+l+'</span>')
    return xs

def first():
    out.insert(0., '←左画面にHtmlに変換したい文章を入力')

def main():
    global app, inp, out
    
    app = t.Tk()
    app.geometry('1300x625')
    app.title('Text to Html 変換アプリ')
    app.resizable(width=False, height=False)
    
    inp = t.Text(app, background='#f0f0e0', font=('Arial',12))
    inp.place(x=0, y=0, width=500, height=600)
    out = t.Text(app, background='#d0d0f8', font=('Arial',12))
    out.place(x=500, y=0, width=800, height=600)

    but = t.Button(text=u'通常変換', background='#ffaaaa')
    but.place(x=5, y=600, width=70, height=20)
    but.bind('<Button-1>', func)
    but_py = t.Button(text=u'Python', background='#ffffff')
    but_py.place(x=75, y=600, width=70, height=20)
    but_py.bind('<Button-1>', func_py)
    but_html = t.Button(text=u'HTML', background='#ffffff')
    but_html.place(x=145, y=600, width=70, height=20)
    but_html.bind('<Button-1>', func_html)
    but_js = t.Button(text=u'JavaScript', background='#ffffff')
    but_js.place(x=215, y=600, width=70, height=20)
    but_js.bind('<Button-1>', func_js)
    but_sp = t.Button(text=u'特殊変換', background='#ffffff')
    but_sp.place(x=285, y=600, width=70, height=20)
    but_sp.bind('<Button-1>', func_sp)
    but['background'] = '#ffffff'
    but_py['background'] = '#ffffff'
    but_html['background'] = '#ffffff'
    but_js['background'] = '#ffffff'
    but_sp['background'] = '#ffffff'
    app.bind('<Key-v>', func)
    
    first()
    
    app.mainloop()

if(__name__ == '__main__'):
    main()







○ 数独・ナンプレ【Python】
copy
sudoku.py
展開
折り畳む
#! /usr/local/bin/env python3
#! encode : -*- utf-8 -*-

"""
"最初にあける数"に「 0 」を入れると答えがすでに埋まった状態で始まる.
分からないマスに「 * 」(アスタリスク)を入力し,[ctrl] + [space]を押すとアスタリスクが答えに置換される.
"""

import numpy as np
import tkinter as t
import random
import sys

def main():
    global nums_9x9, answer
    nums_9x9 = np.zeros((9,9), dtype=int)
    squr = []
    for i in range(0, 9):
        for j in range(0, 9):
            squr.append((i, j))
    while(len(squr) > 0):
        c = 0
        squr = rand_insert(0, squr, nums_9x9)
        squr = rand_insert(3, squr, nums_9x9)
        squr = rand_insert(6, squr, nums_9x9)
        while(c < 81):
            c = c + 1
            zc_TF = zero_count(nums_9x9)
            squr_l = len(squr)
            if(zc_TF and (squr_l >= 0)):
                squr = all_num_set(squr, nums_9x9)
                squr_l = len(squr)
                if(squr_l == 0):
                    break
                r = random.randint(0, squr_l - 1)
                x, y = squr[r]
                n = ok_num(x, y)
                if(n != 0):
                    nums_9x9[squr[r]] = n
                    cl_TF = check_list(n, x, y)
                    if(cl_TF):
                        squr.pop(r)
                    else:
                        nums_9x9[squr[r]] = 0
                        pass
                else:
                    break
            else:
                break
        if(len(squr) == 0):
            break
        nums_9x9 = np.zeros((9,9), dtype=int)
        squr = []
        for i in range(0, 9):
            for j in range(0, 9):
                squr.append((i, j))
    if answer:
        print("Answer :\n{}".format(nums_9x9), end="\n\n") # debug

def zero_count(arraylist):
    for i in range(0, 9):
        for j in range(0, 9):
            n = nums_9x9[(i, j)]
            if(n == 0):
                return True
            else:
                pass
    return False

def row_num_list(x, y):
    num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for i in range(0, 9):
        n = nums_9x9[(x, i)]
        if((y != i) and (n != 0)):
            num_list.remove(n)
    return num_list

def col_num_list(x, y):
    num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for i in range(0, 9):
        n = nums_9x9[(i, y)]
        if((x != i) and (n != 0)):
            num_list.remove(n)
    return num_list

def box_num_list(x, y):
    num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    sets1 = [0, 1, 2]
    sets2 = [-1, 0, 1]
    sets3 = [-2, -1, 0]
    sets_list = [sets1, sets2, sets3]
    x_sets = sets_list[x % 3]
    y_sets = sets_list[y % 3]
    for i in range(0, 3):
        for j in range(0, 3):
            setx = x + x_sets[i]
            sety = y + y_sets[j]
            n = nums_9x9[(setx, sety)]
            if((x != setx or y != sety) and (n != 0)):
                num_list.remove(n)
    return num_list

def row_check(number, x, y):
    c = 0
    for i in range(0, 9):
        if(number == nums_9x9[(x, i)]):
            c = c + 1
        else:
            pass
    if(c == 1):
        return True
    else:
        return False

def col_check(number, x, y):
    c = 0
    for i in range(0, 9):
        if(number == nums_9x9[(i, y)]):
            c = c + 1
        else:
            pass
    if(c == 1):
        return True
    else:
        return False

def box_check(number, x, y):
    sets1 = [0, 1, 2]
    sets2 = [-1, 0, 1]
    sets3 = [-2, -1, 0]
    sets_list = [sets1, sets2, sets3]
    x_sets = sets_list[x % 3]
    y_sets = sets_list[y % 3]
    c = 0
    for i in range(0, 3):
        for j in range(0, 3):
            setx = x + x_sets[i]
            sety = y + y_sets[j]
            n = nums_9x9[(setx, sety)]
            if(number == n):
                c = c + 1
            else:
                pass
    if(c == 1):
        return True
    else:
        return False

def ok_row_num(x, y):
    coordinate_list = []
    collect_list = []
    all_list = []
    for i in range(0, 9):
        if(nums_9x9[(x, i)] == 0):
            row_list = row_num_list(x, i)
            col_list = col_num_list(x, i)
            box_list = box_num_list(x, i)
            l = set(row_list) & set(col_list) & set(box_list)
            and_list = list(l)
            coordinate_list.append((x, i))
            collect_list.append(and_list)
            all_list = all_list + and_list
    for i in range(0, len(coordinate_list)):
        for j in collect_list[i]:
            coorx, coory = coordinate_list[i]
            c = all_list.count(j)
            if((x == coorx) and (y == coory) and (c == 1)):
                return j
    return 0

def ok_col_num(x, y):
    coordinate_list = []
    collect_list = []
    all_list = []
    for i in range(0, 9):
        if(nums_9x9[(i, y)] == 0):
            row_list = row_num_list(i, y)
            col_list = col_num_list(i, y)
            box_list = box_num_list(i, y)
            l = set(row_list) & set(col_list) & set(box_list)
            and_list = list(l)
            coordinate_list.append((i, y))
            collect_list.append(and_list)
            all_list = all_list + and_list
    for i in range(0, len(coordinate_list)):
        for j in collect_list[i]:
            coorx, coory = coordinate_list[i]
            c = all_list.count(j)
            if((x == coorx) and (y == coory) and (c == 1)):
                return j
    return 0

def ok_box_num(x, y):
    sets1 = [0, 1, 2]
    sets2 = [-1, 0, 1]
    sets3 = [-2, -1, 0]
    sets_list = [sets1, sets2, sets3]
    x_sets = sets_list[x % 3]
    y_sets = sets_list[y % 3]
    coordinate_list = []
    collect_list = []
    all_list = []
    for i in range(0, 3):
        for j in range(0, 3):
            setx = x + x_sets[i]
            sety = y + y_sets[j]
            if(nums_9x9[(setx, sety)] == 0):
                row_list = row_num_list(setx, sety)
                col_list = col_num_list(setx, sety)
                box_list = box_num_list(setx, sety)
                l = set(row_list) & set(col_list) & set(box_list)
                and_list = list(l)
                coordinate_list.append((setx, sety))
                collect_list.append(and_list)
                all_list = all_list + and_list
    for i in range(0, len(coordinate_list)):
        for j in collect_list[i]:
            coorx, coory = coordinate_list[i]
            c = all_list.count(j)
            if((x == coorx) and (y == coory) and (c == 1)):
                return j
    return 0

def ok_num(x, y):
    row_list = row_num_list(x, y)
    col_list = col_num_list(x, y)
    box_list = box_num_list(x, y)
    l = set(row_list) & set(col_list) & set(box_list)
    and_list = list(l)
    if(len(and_list) == 0):
        return 0
    else:
        row_num = ok_row_num(x, y)
        col_num = ok_col_num(x, y)
        box_num = ok_box_num(x, y)
        row_num_TF = row_num in and_list
        col_num_TF = col_num in and_list
        box_num_TF = box_num in and_list
        if(row_num_TF):
            return row_num
        else:
            if(col_num_TF):
                return col_num
            else:
                if(box_num_TF):
                    return box_num
                else:
                    r = random.randrange(0, len(and_list))
                    return and_list[r]

def row_only_check(number, x, y):
    row_only_list = []
    for i in range(0, 9):
        row_list = row_num_list(x, i)
        col_list = col_num_list(x, i)
        box_list = box_num_list(x, i)
        l = set(row_list) & set(col_list) & set(box_list)
        and_list = list(l)
        row_only_list.append(and_list)
    for i in range(0, 9):
        rolist = row_only_list[i]
        if((y != i) and (len(rolist) == 1) and (rolist[0] == number)):
            return False
    return True

def col_only_check(number, x, y):
    col_only_list = []
    for i in range(0, 9):
        row_list = row_num_list(i, y)
        col_list = col_num_list(i, y)
        box_list = box_num_list(i, y)
        l = set(row_list) & set(col_list) & set(box_list)
        and_list = list(l)
        col_only_list.append(and_list)
    for i in range(0, 9):
        colist = col_only_list[i]
        if((x != i) and (len(colist) == 1) and (colist[0] == number)):
            return False
    return True

def box_only_check(number, x, y):
    box_only_list = []
    sets1 = [0, 1, 2]
    sets2 = [-1, 0, 1]
    sets3 = [-2, -1, 0]
    sets_list = [sets1, sets2, sets3]
    x_sets = sets_list[x % 3]
    y_sets = sets_list[y % 3]
    for i in range(0, 3):
        for j in range(0, 3):
            setx = x + x_sets[i]
            sety = y + y_sets[j]
            row_list = row_num_list(setx, sety)
            col_list = col_num_list(setx, sety)
            box_list = box_num_list(setx, sety)
            l = set(row_list) & set(col_list) & set(box_list)
            and_list = list(l)
            box_only_list.append(and_list)
    count = 0
    for i in range(0, 3):
        for j in range(0, 3):
            bolist = box_only_list[count]
            count = count + 1
            setx = x + x_sets[i]
            sety = y + y_sets[j]
            if((x != setx or y != sety) and (len(bolist) == 1) and (bolist[0] == number)):
                return False
    return True

def rand_insert(place, squr, nums_9x9_list):
    global erasure1,erasure2,number,st
    num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    random.shuffle(num_list)
    squr_li = []
    for i in range(0, 3):
        for j in range(0, 3):
            squr_li.append((i + place, j + place))
    while(len(squr_li) > 0):
        r = random.randrange(0, len(squr_li))
        x, y = squr_li[r]
        count = 0
        while(True):
            try:
                squrx, squry = squr[count]
            except IndexError:
                st["text"] = "エラー"
                sys.exit()
            if((x == squrx) and (y == squry)):
                nums_9x9_list[(x, y)] = num_list[r]
                erasure1 = squr.pop(count)
                erasure2 = squr_li.pop(r)
                number = num_list.pop(r)
                break
            else:
                count = count + 1
    return squr

def check_list(n, x, y):
    rc_TF = row_check(n, x, y)
    cc_TF = col_check(n, x, y)
    bc_TF = box_check(n, x, y)
    roc_TF = row_only_check(n, x, y)
    coc_TF = col_only_check(n, x, y)
    boc_TF = box_only_check(n, x, y)
    if(rc_TF and (cc_TF and (bc_TF and (roc_TF and (coc_TF and (boc_TF)))))):
        return True
    return False

def row_only_set(squr, nums_9x9):
    global erasure
    for i in range(0, 9):
        coordinate_list = []
        collect_list = []
        all_list = []
        for j in range(0, 9):
            if(nums_9x9[(i, j)] == 0):
                row_list = row_num_list(i, j)
                col_list = col_num_list(i, j)
                box_list = box_num_list(i, j)
                l = set(row_list) & set(col_list) & set(box_list)
                and_list = list(l)
                coordinate_list.append((i, j))
                collect_list.append(and_list)
                all_list = all_list + and_list
        for k in range(0, len(all_list)):
            c = all_list.count(all_list[k])
            if(c == 1):
                for coor in range(0, len(collect_list)):
                    TF = all_list[k] in collect_list[coor]
                    if(TF):
                        coorx, coory = coordinate_list[coor]
                        nums_9x9[(coorx, coory)] = all_list[k]
                        count_up = 0
                        clist = len(squr)
                        while(clist > count_up):
                            squrx, squry = squr[count_up]
                            if((coorx == squrx) and (coory == squry)):
                                erasure = squr.pop(count_up)
                                count_up = count_up - 1
                                break
                            else:
                                pass
                            count_up = count_up + 1
                            clist = len(squr)
    return squr

def col_only_set(squr, nums_9x9):
    global erasure
    for i in range(0, 9):
        coordinate_list = []
        collect_list = []
        all_list = []
        for j in range(0, 9):
            if(nums_9x9[(j, i)] == 0):
                row_list = row_num_list(j, i)
                col_list = col_num_list(j, i)
                box_list = box_num_list(j, i)
                l = set(row_list) & set(col_list) & set(box_list)
                and_list = list(l)
                coordinate_list.append((j, i))
                collect_list.append(and_list)
                all_list = all_list + and_list
        for k in range(0, len(all_list)):
            c = all_list.count(all_list[k])
            if(c == 1):
                for coor in range(0, len(collect_list)):
                    TF = all_list[k] in collect_list[coor]
                    if(TF):
                        coorx, coory = coordinate_list[coor]
                        nums_9x9[(coorx, coory)] = all_list[k]
                        count_up = 0
                        clist = len(squr)
                        while(clist > count_up):
                            squrx, squry = squr[count_up]
                            if((coorx == squrx) and (coory == squry)):
                                erasure = squr.pop(count_up)
                                count_up = count_up - 1
                                break
                            else:
                                pass
                            count_up = count_up + 1
                            clist = len(squr)
    return squr

def box_only_set(squr, nums_9x9):
    global erasure
    sets1 = [0, 1, 2]
    sets2 = [-1, 0, 1]
    sets3 = [-2, -1, 0]
    sets_list = [sets1, sets2, sets3]
    count_all = 0
    clist = len(squr)
    while(clist > count_all):
        boxx, boxy = squr[count_all]
        x_sets = sets_list[boxx % 3]
        y_sets = sets_list[boxy % 3]
        coordinate_list = []
        collect_list = []
        all_list = []
        for i in range(0, 3):
            for j in range(0, 3):
                setx = boxx + x_sets[i]
                sety = boxy + y_sets[j]
                if(nums_9x9[(setx, sety)] == 0):
                    row_list = row_num_list(setx, sety)
                    col_list = col_num_list(setx, sety)
                    box_list = box_num_list(setx, sety)
                    l = set(row_list) & set(col_list) & set(box_list)
                    and_list = list(l)
                    coordinate_list.append((setx, sety))
                    collect_list.append(and_list)
                    all_list = all_list + and_list
        for k in range(0, len(all_list)):
            c = all_list.count(all_list[k])
            if(c == 1):
                for coor in range(0, len(collect_list)):
                    TF = all_list[k] in collect_list[coor]
                    if(TF):
                        coorx, coory = coordinate_list[coor]
                        nums_9x9[(coorx, coory)] = all_list[k]
                        count_up = 0
                        clist = len(squr)
                        while(clist > count_up):
                            squrx, squry = squr[count_up]
                            if((coorx == squrx) and (coory == squry)):
                                erasure = squr.pop(count_up)
                                count_up = count_up - 1
                                break
                            else:
                                pass
                            count_up = count_up + 1
                            clist = len(squr)
        count_all = count_all + 1
        clist = len(squr)
    return squr

def all_num_set(squr, nums_9x9):
    while True:
        row_squr = row_only_set(squr, nums_9x9)
        col_squr = col_only_set(squr, nums_9x9)
        box_squr = box_only_set(squr, nums_9x9)
        if(row_squr == col_squr == box_squr):
            break
    return squr

def boo(b):
    if b:
        b = False
    else:
        b = True
    return b

def func(event):
    global ans,now,st,level
    now = boo(now)
    num = level.get()
    try:
        num = int(num)
        if((num < 0) or (num > 100)):
            st["text"] = "最初にあける数字が異常"
        else:
            if now:
                color()
                main()
                ans["text"] = "正解確認"
                ans["background"] = "#DFFFDF"
                global op
                op = []
                if(num > 0):
                    for i in range(num):
                        op.append([random.randint(0,8),random.randint(0,8)])
                    for i in range(9):
                        for k in range(9):
                            ents[i][k].delete(0, t.END)
                            if([i,k] in op):
                                ents[i][k]["foreground"] = "#0000FF"
                                ents[i][k].insert(0, nums_9x9[i][k])
                            else:
                                ents[i][k]["foreground"] = "#000000"
                                ents[i][k].delete(0, t.END)
                else:
                    for i in range(9):
                        for k in range(9):
                            ents[i][k].delete(0, t.END)
                            ents[i][k]["foreground"] = "#0000FF"
                            ents[i][k].insert(0, nums_9x9[i][k])
                st["text"] = "「 * 」を入力\n→ 答え"
            else:
                Fault = True
                ans["text"] = "スタート"
                ans["background"] = "#FFDFDF"
                for i in range(9):
                    for k in range(9):
                        if(not [i,k] in op):
                            inp = ents[i][k].get()
                            try:
                                inp = int(inp)
                            except:
                                st["text"] = "あてはめた数字が異常"
                            out = nums_9x9[i][k]
                            if(inp == out):
                                ents[i][k].delete(0, t.END)
                                ents[i][k]["foreground"] = "#00A000"
                                ents[i][k].insert(0, out)
                            else:
                                Fault = False
                                ents[i][k].delete(0, t.END)
                                ents[i][k]["foreground"] = "#FF0000"
                                ents[i][k].insert(0, out)
                if(Fault):
                    for i in range(9):
                        for k in range(9):
                            ents[i][k]["background"] = "#DFFFDF"
                    st["text"] = "!!全問正解!!\nおめでとう!"
                else:
                    st["text"] = "計算に時間がかかるかも\nそんなときもある"
    except:
        st["text"] = "最初にあける数字が異常"

def color():
    global ents
    booI = False
    for i in range(9):
        if(i % 3 == 0):
            booI = boo(booI)
        booK = False
        for k in range(9):
            if(k % 3 == 0):
                booK = boo(booK)
            if(booK == booI):
                ents[i][k]["background"] = "#D0D0D0"
            else:
                ents[i][k]["background"] = "#FFFFFF"

def hint(event):
    global ents, st
    st["text"] = "知りたい場所に「*」を入力"
    for i in range(9):
        for k in range(9):
            inp = ents[i][k].get()
            if inp == "*":
                ents[i][k].delete(0, t.END)
                ents[i][k].insert(0, nums_9x9[i][k])
                ents[i][k]["foreground"] = "#00A000"

now = False
app = t.Tk()
app.title("Sudoku - 数独")
app.geometry("460x490")
app.resizable(width=False, height=False)
ents = []
bf = []
for i in range(9):
    bf = [t.Entry() for i in range(9)]
    for k in range(9):
        bf[k].place(x=5+50*k, y=5+50*i, width=50, height=50)
        bf[k]["justify"] = t.CENTER
        bf[k]["font"] = ("MS Gothic",30)
    ents.append(bf)
color()
lab = t.Label(text=u"最初にあける数:")
lab.place(x=5, y=462)
level = t.Entry(justify=t.CENTER)
level.place(x=95,y=460, width=40)
level.insert(0, "40")
ans = t.Button(text=u"スタート", background="#FFDFDF")
ans.place(x=135, y=455, width=190, height=35)
ans.bind("<Button-1>", func)
st = t.Label(text=u"計算に時間がかかるかも\nそんなときもある")
st.place(x=325, y=455)
app.bind("<Key>",hint)

# answer = Trueでコンソールに答えを出力
answer = False

app.mainloop()