Python デスクトップアプリ ToDoリスト
# todo list # pythonでデスクトップアプリを作ってみる:1日目 # http://kconputing.hatenablog.com/entry/2017/02/27/235055 import tkinter as Tk class Application(Tk.Frame): def __init__(self, master=None): Tk.Frame.__init__(self, master) self.master.title("Todo List") self.master.geometry("400x300") # 変数初期化 self.ToDoNumber = 0 self.ToDo = [] self.BoolVars = [] # ウィジェットの生成・配置 self.create_widgets() self.pack() def create_widgets(self): #入力フォーム self.EditBox = Tk.Entry(self, width=30) self.EditBox.grid(row=0, column=0) Button_Add = Tk.Button(self, text='追加') Button_Add.bind('<Button-1>', self.DeleteEntryValue) Button_Add.grid(row=0, column=1) Button_Delete = Tk.Button(self, text='タスクを消去') Button_Delete.bind('<Button-1>', self.DeleteTask) Button_Delete.grid(row=0, column=2) def DeleteEntryValue(self, event): # EditBoxに書かれている文字列をtxtNewに代入 txtNew = Tk.StringVar() txtNew.set(self.EditBox.get()) # 新たにラベル(ToDoリスト)を作成 if txtNew.get() == "": return val = Tk.BooleanVar() val.set(False) ToDoNew = Tk.Checkbutton(self, textvariable=txtNew, variable=val) # 新たに作成したToDoをリストに追加 self.ToDo.append(ToDoNew) self.BoolVars.append(val) # 新しいラベルをToDoリストの末尾に追加 self.ToDoNumber += 1 ToDoNew.grid(row=self.ToDoNumber, column=0) # EditBoxに書かれている文字列を消去 self.EditBox.delete(0, Tk.END) def DeleteTask(self, event): delCnt = 0 for i in range(self.ToDoNumber): j = i - delCnt if self.BoolVars[j].get(): self.ToDo[j].destroy() del self.ToDo[j] del self.BoolVars[j] delCnt += 1 self.ToDoNumber -= delCnt root = Tk.Tk() app = Application(master=root) app.mainloop()
Python デスクトップアプリ カラーバー
# tkinter demo # カラーバー # http://www.geocities.jp/m_hiroi/light/pytk01.html # coding: utf-8 from tkinter import * # メインウィンドウ root = Tk() # スケールの値を格納する red = IntVar() red.set(0) blue = IntVar() blue.set(0) green = IntVar() green.set(0) # ボタンの背景色を変更 def change_color( n ): color = '#%02x%02x%02x' % (red.get(), green.get(), blue.get()) button.configure(bg = color) # ボタン button = Button(root, text = 'button', bg = '#000') button.pack(fill = 'both'); # スケール s1 = Scale(root, label = 'red', orient = 'h', from_ = 0, to = 255, variable = red, command = change_color) s2 = Scale(root, label = 'blue', orient = 'h', from_ = 0, to = 255, variable = blue, command = change_color) s3 = Scale(root, label = 'green', orient = 'h', from_ = 0, to = 255, variable = green, command = change_color) # ウィジェットの配置 s1.pack(fill = 'both') s2.pack(fill = 'both') s3.pack(fill = 'both') # メインループ root.mainloop();
Python Webスクレイピング
- Webスクレイピング
# webスクレイピング1 日本経済新聞のHPから日経平均を取得 # https://qiita.com/hirouen/items/7bc7fa05cc2d774edf44 # requests # https://requests-docs-ja.readthedocs.io/en/latest/ # BeautifulSoup # https://www.crummy.com/software/BeautifulSoup/bs4/doc/ # このあたりをひっかけてくる # <div class="m-miH01C_list js-miH01" id="js-ticker_list"><ul><li class="m-miH01C_item"> # <div class="m-miH01C_cell m-miH01C_cell_col5" data-id="JSID_JpnIndex"><a href="/markets/worldidx/chart/nk225/" title="11/13 15:15 大引"><span class="m-miH01C_exchange">日経平均</span><span class="m-miH01C_rate">21,810.52</span><span class="m-miH01C_comparison minus">-459.36</span></a></div> # <div class="m-miH01C_cell m-miH01C_cell_col5" data-id="JSID_DowJones"><a href="/markets/kaigai/" title="11/13 16:20 "><span class="m-miH01C_exchange">NYダウ</span><span class="m-miH01C_rate">25,286.49</span><span class="m-miH01C_comparison minus">-100.69</span></a></div> # <div class="m-miH01C_cell m-miH01C_cell_col5" data-id="JSID_YenDollarExchange"><a href="/markets/kawase/" title="11/14 8:25"><span class="m-miH01C_exchange">ドル円</span><span class="m-miH01C_rate">113.78-79</span><span class="m-miH01C_comparison minus">-0.28</span></a></div> import requests from bs4 import BeautifulSoup url = 'https://www.nikkei.com/' html = requests.get(url) # html.text で全文表示 soup = BeautifulSoup(html.text,"html.parser") span = soup.find_all("span") nikkei_heikin = "" for tag in span: # print(tag) # print(tag.get("class")) string_ = tag.get("class")[0] # <span class="m-wficon triDown"></span> をtag.get("class")すると # ['m-wficon', 'triDown']のように、スペースで分割されてリストになるらしい # 元のコードはstring_ = tag.get("class").Pop(0)としてたが、 # そうするとsoupで持ってるhtmlから当該classが消えてしまう(!)ので # string_ =tag.get("class")[0]とした if string_ in "m-miH01C_rate": nikkei_heikin = tag.string break print(nikkei_heikin) # 21,810.52 (2018/11/14 08:26実行時)
Python Basics
内容
- FizzBuzz
- テキストの読み書き
- ファイル操作
- exeファイルの実行
# FizzBuzz def fizzbuzz(x): if x % 15 == 0: return "fizzbuzz" elif x % 3 == 0: return "fizz" elif x % 5 == 0: return "buzz" else: return str(x) a = [fizzbuzz(x) for x in range(1,41)] print(a[:10]) print(a[10:20]) print(a[20:30]) print(a[30:40]) #['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz'] #['11', 'fizz', '13', '14', 'fizzbuzz', '16', '17', 'fizz', '19', 'buzz'] #['fizz', '22', '23', 'fizz', 'buzz', '26', 'fizz', '28', '29', 'fizzbuzz'] #['31', '32', 'fizz', '34', 'buzz', 'fizz', '37', '38', 'fizz', 'buzz']
- テキストの読み書き
# Write and Read def write_test(): with open("test.txt", mode = 'w') as f: f.write("a\n") for e in ["b", "cd"]: f.write(e + "\n") # f.writelines(["b", "cd"]) は改行されない def read_test(): with open("test.txt", mode = 'r') as f: bufs = [s.strip() for s in f.readlines()] for b in bufs: print(b) write_test() read_test() # a # b # cd
- ファイル操作
# fileio import os import shutil # フォルダ作成 print("フォルダ作成") if os.path.isdir("sample"): print("sample is already made.") else: os.mkdir("sample") print(os.listdir()) print() # 空テキストの作成 print("空テキストの作成") with open("sample/test.txt", mode = 'w') as f: pass print(os.listdir("sample")) print() # ファイルコピー print("ファイルコピー") shutil.copy2("sample/test.txt", "sample/text2.txt") #copy2はメタデータ(ファイル作成日等)もコピー print(os.listdir("sample")) print() # ファイル削除 print("ファイル削除") os.remove("sample/test.txt") print(os.listdir("sample")) print() # フォルダ削除 print("フォルダ削除") shutil.rmtree("sample") # 中身があっても削除 print(os.listdir()) print() # フォルダ作成 # ['.ipynb_checkpoints', 'basics.ipynb', 'sample', 'test.txt'] # 空テキストの作成 # ['test.txt'] # ファイルコピー # ['test.txt', 'text2.txt'] # ファイル削除 # ['text2.txt'] # フォルダ削除 # ['.ipynb_checkpoints', 'basics.ipynb', 'test.txt']
- exeファイルの実行
# run exe import subprocess excel_path = r"C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE" subprocess.Popen(excel_path) # エクセルが起動する # Popenはアプリが起動したらすぐ制御を返す(プロセス終了を待たない)