2016.03.10

『確かな力が身につくPython「超」入門』内の実行コードについて

確かな力が身につくPython「超」入門

この度は『確かな力が身につくPython「超」入門』をお買い上げいただきありがとうございます。
本書内で取り扱っているサンプルコードは下記よりコピー&ペーストにてお試していただけます。


1-3

python 

import calendar

print(calendar.month(2015,5))

 



 

1-4

import this

 




 

2-2

1129 + 2344

3473 + 376

400 – 330

 


 

 

2800 * 1.08

1920 / 12

 


 

 

(40 + 50) * 3 – 50

40 + 50 * 3 – 50

 


255 % 3

255 % 7


2 ** 3

5 ** 4


(4 + 5j) – (3 – 4j)

1J ** 2



2-3

tax = 0.08

price = 120

suzuki_telephone = ‘090-1234-5678’


tax

price

suzuki_telephone


price * tax

120 * 0.08



2-4

34 > 22 

34 < 22


apple = 15

apple == 15


 ”’

Sunday

Monday

Tuesday

”’



‘thunder’ + ‘bolt’


‘hunter’ * 2


text = ‘hello’

text.upper()


word = ‘maintenance’

word.count(‘n’)


46 < 49

46 > 49


Agroup = [‘kazu’, ‘gorou’]

Agroup.append(‘dai’)

Agroup

 


Agroup = [‘kazu’, ‘gorou’, ‘dai’]

Agroup.remove(‘kazu’)

Agroup

 


Agroup = [‘kazu’, ‘gorou’, ‘dai’]

Agroup.sort()

Agroup

 


test_result = [87, 55, 99, 50, 66, 78]

test_result.sort()

test_result

 


activities = {‘Monday’:’バスケ’, ‘Tuesday’:’自転車’, ‘Wednesday’:’軽音’,’Friday’:’水泳’}

activities[‘Tuesday’]

activities[‘Friday’]


 

activities.keys()

activities.values()

 


tuple = (‘apple’, 3, 90.4)

print(tuple)

 


list = [‘ミント’, ‘チョコ’, ‘ストロベリー’, ‘バニラ’]

list[0] = ‘ラムレーズン’

print(list)

 


tuple = (‘ミント’, ‘チョコ’, ‘ストロベリー’, ‘バニラ’)

tuple[0] = ‘ラムレーズン’ #TypeErrorになる

 


print(tuple)

(‘ミント’, ‘チョコ’, ‘ストロベリー’, ‘バニラ’)

 


diary = {}

key = (‘kamata’, ’08-01′)

diary[key] = ’70kg’

print(diary)

 


diary = {}

key = [‘nakata’, ’08-01′]

diary[key] = ’50kg’#TypeErrorになる

 


candy = {‘delicious’, ‘fantastic’}

print(candy)

 


candy = set(‘delicious’)

print(candy)

 


flavor = [‘apple’, ‘peach’, ‘soda’]

candy = set(flavor)

candy

 


candy.update([‘grape’])

candy

 


flavor = [‘apple’, ‘soda’, ‘chocolate’, ‘apple’, ‘grape’, ‘grape’,’soda’]

flavor_set = set(flavor)

print(flavor_set)

 


flavor = list(flavor_set)

print(flavor)

 


flavor_set_A = {‘apple’, ‘peach’, ‘soda’}

flavor_set_B = {‘apple’, ‘soda’, ‘chocolate’}

flavor_set_A – flavor_set_B

 

flavor_set_A & flavor_set_B

 




3-1

age = 29

if (18 <= age):

              print(‘チケットを売る’)


age = 15

if (18 <= age):

              print(‘チケットを売る’)

 


age = 15

if (18 <= age):

              print(‘チケットを売る’)

else:

              print(‘チケットを売ることはできません’)

 


 

 

age=70

if (60<=age):

              print (‘チケットは1000円です’)

 elif (18<=age):

              print (‘チケットは1800円です’)

 else:

              print (‘チケットを売ることはできません’)

 


 

 

age=70

 if (18<=age):

              print (‘チケットは1800円です’)

 elif (60<=age):

              print (‘チケットは1000円です’)

 else:

              print (‘チケットを売ることはできません’)

 


 

 

age=70

if (18 <= age <= 59):

              print(‘チケットは1800円です’)

 elif (60 <= age):

              print(‘チケットは1000円です’)

 else:

              print(‘チケットを売ることはできません’)

 


 

pointcard = True

count = 5

if (pointcard == True):

              if (count == 5):

                            print (‘いつもありがとうございます。今回は1000円です’)

 


 

 

pointcard = True

count = 5

(pointcard == True)

 

(count == 5)

 

((pointcard == True) and (count == 5))

 

pointcard = False

count = 5

(pointcard == True)

 

(count == 5)

 

((pointcard == True) and (count == 5))

 

pointcard = True

count = 5

if ((pointcard == True) and (count == 5)):

              print(‘いつもありがとうございます。今回は1000円です’)

 

 


 

 

age = 35

pointcard=True

count=5

if (age < 18):

              print(‘チケットを売ることはできません’)

 elif ((60 <= age) or ((pointcard == True) and (count == 5))):

              print(‘チケットは1000円です’)

 else:

              print(‘チケットは1800円です’)

 



 

 

3-2

for count in range(3):

              print(‘繰り返します’)

              print(count)

 


 

 

word = ‘ninja’

for chara in word:

              print(chara)

 


 

 

music_list = [‘DEATH METAL’, ‘ROCK’, ‘ANIME’, ‘POP’]

for music in music_list:

              print(‘now playing ‘ + music)

 


 

 

menu = {‘ラーメン’:500, ‘チャーハン’:430, ‘餃子’:210}

for order in menu:

              print(order)

              print(menu[order] * 1.08)

 


 

 

counter = 0

while (counter < 5:)

              print(counter)

              counter = counter + 1

 


 

 

counter = 0

while (counter < 5):

              print(counter)

 

while(True):

              print(‘たたかう’)

 

while(True):

              print(‘パンチ’)

              print(‘キック’)

              break

              print(‘必殺奥義’)

 

power = 2

while(True):

              print(‘パンチ’)

              print(‘キック’)

              print(‘必殺奥義’)

              power = power -1

              if (power == 0):

                            break

 

 


 

 

family = [‘ryu-ko’, ‘mako’, ‘satsuki’]

for kid in family:

              print(‘おはよう!’ + kid)

              print(‘起床’)

              print(‘朝ごはん’)

              continue

              print(‘学校に出発’)

 



 

 

3-3

def washingMachine():

              print(‘給水します’)

              print(‘洗います’)

              print(‘すすぎます’)

              print(‘脱水します’)

              print(‘乾燥します’)

 

 

washingMachine()

 


 

 

 

def softWash ():

              print(‘給水します’)

              print(‘やさしく洗います’)

              print(‘すすぎます’)

              print(‘脱水します’)

              print(‘乾燥します’)

 


 

 

mode = ‘soft’

if (mode == ‘soft’):

              print(‘やさしく洗う’)

 elif (mode == ‘hard’):

              print(‘激しく洗う’)

 else:

              print(‘ふつうに洗う’)

 

 


 

 

def washingMachine(mode):

              print(‘給水します’)

              if (mode == ‘soft’):

                            print(‘やさしく洗う’)

              elif (mode == ‘hard’):

                            print(‘激しく洗う’)

              else:

                            print(‘ふつうに洗う’)

 

washingMachine(‘soft’)

 

washingMachine(‘hard’)

 

washingMachine(‘normal’)

 


 

 

def area(radius):

              result = radius * radius * 3.14

              return result

 

area(5)

 

small = area(5)

big = area(10)

print(small)

 

print(big)

 


 

 

len(‘thunderbolt’)

 


 

 

animal = [‘cat’,’dog’, ‘duck’]

len(animal)

 


 

 

max(100,10,50)

 

min(300,30,3000)

 


 

 

max(‘thunderbolt’)

 


 

 

min(‘1Aa’)

 

max(‘1Aa’)

 


 

 

sorted(‘thunderbolt’)

 

sorted(‘1Aa’)

 

sorted([100, 95, 55, 78, 80, 78])

 



print(988+12)

 

 

print(‘Hey! World’)

 

hatena_1 = 9800

 


 

 

type(hatena_1)

 

hatena_2 = ‘marshmallow’

type(hatena_2)

 

hatena_3 = [‘osomatsu’, ‘karamatsu’]

type(hatena_3)

 

string = ‘nikuman’

dir(string)

 

dir()

 



 

 

3-4

print(‘hello) #SyntaxErrorになる

 


 

 

try:

              prin(‘例外が発生してしまう処理’)

 except:

              print(‘例外をキャッチしました’)

 


 

 

try:

              orin

              prin

 except:

              print(‘安心してください。大丈夫です’)

 

try:

              prin(‘a’)

 except Exception as e:

              print(e.args)

 




 

 

4-1

 

class fruit:

              color = ‘red’

              def taste(self):

                            return ‘delicious’

apple = fruit()

apple.color

 

apple.taste()

 


 

 

color = ‘green’

color.count(‘e’)

 


 

 

color = ‘green’

color.upper()

 


 

 

class staff:

              def salary():

                            return “10000yen”

 

yamamoto = staff()

yamamoto.salary() #TypeErrorになる

 


 

 

class staff:

              def salary(self):

                            return “10000yen”

 

yamamoto = staff()

yamamoto.salary()

 


 

 

class staff:

              bonus = 30000

              def salary(self):

                            salary = 10000 + bonus

                            return salary

 


 

 

yamamoto = staff()

yamamoto.salary() #NameErrorになる

 


 

 

class staff:

              bonus = 30000

              def salary(self):

                            salary = 10000 + self.bonus

                            return salary

 

yamamoto = staff()

yamamoto.salary()

 

class staff:

              def __init__(self, bonus):

                            self.bonus = bonus

              def salary(self):

                            salary = 10000 + self.bonus

                            return salary

 

yamamoto = staff(50000)

yamamoto.salary()

 


 

class animalBaseClass:

              animallegs=4

              def walk(self):

                            print(‘あるく’)

              def cry(self):

                            print(‘なく’)

              def getLegsNum(self):

                            print(self.animallegs)

 


 

 

class dogClass(animalBaseClass):

              def __init__(self):

                            print(‘いぬです’)

 

wanko = dogClass()

wanko.walk()

wanko.cry()

wanko.getLegsNum()

 

class animalBaseClass:

              animallegs=2

              def walk(self):

                            print(‘あるく’)

              def cry(self):

                            print(‘なく’)

 

class birdClass(animalBaseClass):

              def __init__(self):

                            print(‘とりです’)

              def cry(self):

                            print(‘ぴよぴよ’)

 

piyo_suke = birdClass()

 

piyo_suke.walk()

 

piyo_suke.cry()

 

class animalBaseClass():

              def __init__(self, num):

                            self.animallegs = num

              def walk(self):

                            print(‘あるく’)

              def cry(self):

                            print(‘なく’)

              def getLegsNum(self):

                            print(self.animallegs)

 

class snakeClass(animalBaseClass):

              def __init__(self, num):

                            parent_class = super(snakeClass, self)

                            parent_class.__init__(num)

                            print(‘へびです’)

 

nyoro = snakeClass(0)

 

nyoro.getLegsNum()

 

class snakeClass(animalBaseClass):

              def __init__(self):

                            snake_legs = 0

                            parent_class = super(snakeClass, self)

                            parent_class.__init__(snake_legs)

                            print(‘へびです’)

 

nyoro = snakeClass()

 

nyoro.getLegsNum()

 

 



 

 

4-3

import calendar

print( calendar.month(2015, 7) )

 


 

 

import calendar as cal

print(cal.month(2015, 8))

 


 

 

from calendar import month, isleap

print(month(2015, 9))

 


 

 

from datetime import date

date.today()

 


 

 

from datetime import date

today = date.today()

today.strftime(‘%Y%m%d’)

 

today.strftime(‘%y/%m/%d’)

 

today.strftime(‘%Y年%m月%d日’)

 

today.strftime(‘%Y %B %d %a’)

 

from datetime import datetime

datetime.now()

 


 

 

from datetime import datetime as dt

now = dt.now()

now.strftime(‘%Y-%m-%d %H:%m:%S’)

 

from datetime import date, timedelta

today = date.today()

today

one_week = timedelta(days = 7)

today + one_week

today – one_week

 


 

 

import zipfile

files = zipfile.ZipFile(‘python-3.5.0-embed-win32.zip’)

files.namelist()

files.extractall()

files.close()

 


 

import zipfile

zip_file = zipfile.ZipFile(‘python_code.zip’, mode=’w’)

zip_file.write(‘python.exe’, ‘python’)

zip_file.close()

file = zipfile.ZipFile(‘python_code.zip’)

file.namelist()

 




5-1

 

【Windows】

(コマンドプロンプトで実行)

cd

dir

 

(ユーザーフォルダ上で実行)

cd Desktop

 

(Desktopフォルダ上で実行)

mkdir py_folder

 

【Mac】

(ターミナルで実行)

pwd

 

ls

 

(ユーザーフォルダ上で実行)

cd Desktop/

pwd

ls

 

(Desktopフォルダ上で実行)

mkdir python_folder

ls

python_folder

 

【Windows】

cd Desktop

mkdir py_folder

cd py_folder

python

 

【Mac】

cd Desktop/

mkdir py_folder

cd py_folder/

python3

 



 

 

5-4

open(‘null.txt’, ‘r’) #FileNotFoundErrorになる

 

file_object = open(‘python.txt’, ‘w’)

file_object.write(‘this is sample of python.’)

file_object.close()

file_object.write(‘this is sample of python.’) #ValueErrorになる

 

file_object = open(‘python.txt’, ‘w’)

file_object.write(‘this is sample of python.’)

file_object.flush()

 

file_object = open(‘python.txt’, ‘r’)

file_object.read()

 

【Windows】

file_object = open(‘C:¥¥Users¥¥ユーザー名¥¥Desktop¥¥py_folder¥¥python.txt’,’r’)

file_object.read()

 

【Mac】

file_object = open(‘/Users/ユーザー名/Desktop/py_folder/python.txt’, ‘r’)

file_object.read()

 

file_object = open(‘python.txt’, ‘a’)

file_object.write(‘Add data from program!!’)

file_object.close()

 

file_object = open(‘python.txt’, ‘r+’)

file_object.read()

 

file_object.write(‘Add data from program!!’)

file_object.read()

file_object.close()

 

file_object = open(‘python.txt’, ‘r+’)

file_object.read()

file_object.read()

 

file_object.write(‘Add data from program!!’)

 

 

file_object.seek(0)

 

file_object.read()

 

file_object.close()

 

with open(‘with.txt’, ‘w’) as file_object:

              file_object.write(‘using with!’)

 

obj = open(‘python.txt’, ‘r’)

obj.write(‘can I take it?’) #io.UnsupportedOperation: not writableとなる

 

 




 

 

6-1

pip show Pillow



 

 

6-2

【Windows】

pip install Pillow

 

【Mac】

pip3 install Pillow


 

 

from PIL import Image

image = Image.open(‘sample_image/flower.jpg’)

image.show()


 

 

from PIL import Image

image = Image.open(‘sample_image/flower.jpg’)

r, g, b = image.split()

convert_image = Image.merge(“RGB”, (b, g, r))

convert_image.show()

convert_image.save(‘sample_image/rgb_to_bgr.jpg’);


 

 

from PIL import Image

image = Image.open(‘sample_image/flower.jpg’)

black_and_white = image.convert(‘1’)

black_and_white.show()

black_and_white.save(‘sample_image/b_and_w.jpg’)


 

 

from PIL import Image

image = Image.open(‘sample_image/flower.jpg’)

gray_image = image.convert(“L”)

gray_image.show()

gray_image.save(‘sample_image/gray_image.jpg’)


 

 

from PIL import Image

image = Image.open(‘sample_image/flower.jpg’)

image.transpose(Image.ROTATE_90).show()

image.transpose(Image.ROTATE_90).save(‘rotate_90.jpg’)



 

 

6-3

【Windows】

pip install requests

 

【Mac】

pip3 install requests


 

 

import requests

r = requests.get(‘http://www.yahoo.co.jp’)

print(r.text)


 

 

import requests

import pprint

r = requests.get(‘http://www.yahoo.co.jp’)

pprint.pprint(r.text)

 


 

import requests

import pprint

api_url = ‘http://weather.livedoor.com/forecast/webservice/json/v1?city=130010’;

weather_data = requests.get(api_url).json()

pprint.pprint(weather_data)

 

weather_data.keys()

 

pprint.pprint(weather_data[‘forecasts’][0])


 python get_weather1.py

 

 

【get_weather1.pyの内容】

import requests

api_url = ‘http://weather.livedoor.com/forecast/webservice/json/v1’;

payload={‘city’:’130010′}

weather_data = requests.get(api_url, params=payload).json()

print(weather_data[‘forecasts’][0][‘dateLabel’] + ‘の天気は、’ + weather_

data[‘forecasts’][0][‘telop’])


 

 

【get_weather2.pyの内容】

import requests

api_url = ‘http://weather.livedoor.com/forecast/webservice/json/v1’

payload = {‘city’:’130010′}

weather_data = requests.get(api_url, params = payload).json()

print(weather_data[‘forecasts’][0][‘dateLabel’] + ‘の天気は、’

+ weather_data[‘forecasts’][0][‘telop’])

print(weather_data[‘forecasts’][1][‘dateLabel’] + ‘の天気は、’

+ weather_data[‘forecasts’][1][‘telop’])

print(weather_data[‘forecasts’][2][‘dateLabel’] + ‘の天気は、’

+ weather_data[‘forecasts’][2][‘telop’])


 

 

python3 get_weather3.py

【get_weather3.pyの内容】

import requests

api_url = ‘http://weather.livedoor.com/forecast/webservice/json/v1’

payload={‘city’ : ‘130010’}

weather_data = requests.get(api_url, params = payload).json()

for weather in weather_data[‘forecasts’]:

              print(weather[‘dateLabel’] + ‘の天気は、’ + weather[‘telop’])


 

 

【get_weather4.pyの内容】

import requests

api_url = ‘http://weather.livedoor.com/forecast/webservice/json/v1’

payload = {‘city’ : ‘130010’}

weather_data = requests.get(api_url, params = payload).json()

for weather in weather_data[‘forecasts’]:

              print(weather)


 

 

import requests, pprint

api_url = ‘https://ja.wikipedia.org/w/api.php’

api_params = {‘format’:’json’, ‘action’:’query’, ‘titles’:’椎名林檎’,’prop’:’revisions’, ‘rvprop’:’content’}

wiki_data = requests.get(api_url, params=api_params).json()

pprint.pprint(wiki_data)


 

 

import webbrowser

url = ‘https://ja.wikipedia.org/w/api.php’

webbrowser.open(url)


 

 

python wiki1.py

 

【wiki1.pyの内容】

import requests

import codecs #Windowsの場合

api_base_url = ‘https://ja.wikipedia.org/w/api.php’

api_params = {‘format’:’xmlfm’, ‘action’:’query’, ‘titles’:’椎名林檎’,’prop’:’revisions’, ‘rvprop’:’content’}

wiki_data = requests.get(api_base_url, params=api_params)

fo = codecs.open(‘C:¥¥Users¥¥ユーザー名¥¥Desktop¥¥wiki.html’,’w’, ‘utf-8’) #Windowsの場合

fo = open(‘/Users/ユーザー名/Desktop/wiki.html’, ‘w’) #Macの場合

fo.write(wiki_data.text)

fo.close()


 

 

python try_sys.py one two three four!

【try_sys.pyの内容】

import sys

print(sys.argv)

 

【wiki2.pyの内容】

import requests, sys

import codecs #Windowsの場合

search_word = sys.argv[1]

api_url = ‘https://ja.wikipedia.org/w/api.php’

api_params = {‘format’:’xmlfm’, ‘action’:’query’, ‘prop’:’revisions’,’rvprop’:’content’}

api_params[‘titles’] = search_word

wiki_data = requests.get(api_url, params=api_params)

fo = codecs.open(‘C:¥¥Users¥¥(ユーザー名)¥¥Desktop¥¥’+ search_word+ ‘.html’, ‘w’, ‘utf-8’) #Windowsの場合

fo = open(‘/Users/(ユーザー名)/Desktop/’+ search_word + ‘.html’, ‘w’) #Macの場合

fo.write(wiki_data.text)

fo.close()


 

 

python wiki2.py 東京事変



 

 

6-4

【Windows】

pip install beautifulsoup4

 

【Mac】

pip3 install beautifulsoup4


 

 

from bs4 import BeautifulSoup

soup = BeautifulSoup(“<html> Lollipop </html>”, “html.parser”)


 

 

import requests

from bs4 import BeautifulSoup

html_data = requests.get(‘http://yahoo.co.jp’)

soup = BeautifulSoup(html_data.text,”html.parser”)

soup.title

 


 

import requests

from bs4 import BeautifulSoup

yahoo_tech_news_xml = requests.get(‘http://news.yahoo.co.jp/pickup/computer/rss.xml’)

soup = BeautifulSoup(yahoo_tech_news_xml.text, “html.parser”)

type(soup)

soup.findAll(‘item’)


 import requests

 

from bs4 import BeautifulSoup

yahoo_tech_news_xml = requests.get(‘http://news.yahoo.co.jp/pickup/computer/rss.xml’)

soup = BeautifulSoup(yahoo_tech_news_xml.text, “html.parser”)

type(soup)

soup.findAll(‘item’)

 

for news in soup.findAll(‘item’):

              print(news.title)


 

 

import requests

from bs4 import BeautifulSoup

game_ranking_html=requests.get(‘http://www.amazon.co.jp/gp/new-releases/videogames/637394’)

soup = BeautifulSoup(game_ranking_html.text, “html.parser”)

soup.find(class_=’zg_itemRow’).find(class_=’zg_title’).find(‘a’).string

 

for game in soup.findAll(class_=’zg_itemRow’):

              print(game.find(class_=’zg_rankNumber’).string + game.find(class_=’zg_title’).find(‘a’).string)

 



 

6-5

import newyear1

【newyear1.pyの内容】

print(‘happy new year !!’)


 dir() 

 



print(__name__) 

 


 

import newyear2

【newyear2.pyの内容】

print(__name__)


 

 

import newyear3

【newyear3.pyの内容】

if __name__ == ‘__main__’:

              print(‘happy new year !!’)

 


 

import monthname

monthname.japanese(1)

monthname.japanese(8)

monthname.japanese(12)

 

【monthname.pyの内容】

def japanese(month):

              month_name = {

              1:”霜月”, 2:”如月”, 3:”弥生”, 4:”卯月”, 5:”皐月”, 6:”水無月”,7:”文月”, 8:”葉月”, 9:”長月”, 10:”神無月”, 11:”霜月”, 12:”師走”

              }

              try:

                            response = month_name[month]

              except:

                            response = ‘月の数字を入力してください’

              return response

if __name__ == ‘__main__’:

              print(‘これはモジュール用のファイルです。importして使ってください’)

 


 

 

monthname.japanese(15)

 

monthname.japanese(‘nyan’)

 


 

 

python monthname.py

 


 

import calendar

print(calendar.__file__)

  

 




 

7-1

import tkinter as tk

base = tk.Tk()

base.mainloop()

 


 

import tkinter as tk

base = tk.Tk()

button = tk.Button(base, text=’PUSH!’)

button.pack()

 


 

import tkinter as tk

base = tk.Tk()

button1 = tk.Button(base, text=’push1′)

button2 = tk.Button(base, text=’push2′)

button3 = tk.Button(base, text=’push3′)

button1.pack()

button2.pack()

button3.pack()

 


 

import tkinter as tk

base = tk.Tk()

button1 = tk.Button(base, text=’push1′, width=20).pack()

button2 = tk.Button(base, text=’push2′, width=20).pack(side=tk.LEFT)

button3 = tk.Button(base, text=’push3′, width=20).pack(side=tk.RIGHT)

 


 

import tkinter as tk

base = tk.Tk()

button1 = tk.Button(base, text=’push1′)

button2 = tk.Button(base, text=’push2′)

button3 = tk.Button(base, text=’push3′)

button1.grid(row=0, column=0)

button2.grid(row=0, column=1)

button3.grid(row=1, column=1)

 


 

import tkinter as tk

base = tk.Tk()

button1 = tk.Button(base, text=’push1′)

button2 = tk.Button(base, text=’push2′)

button3 = tk.Button(base, text=’push3′)

button1.place(x=0, y=0)

button2.place(x=50, y=30)

button3.place(x=100, y=60)

 


 

import tkinter as tk

base = tk.Tk()

def push():

              print(‘MELON !’)

 

button = tk.Button(base, text=”WATER”, command=push).pack()

 


 

import tkinter as tk

base=tk.Tk()

tk.Label(base, text=’赤’, bg=’red’, width=20).pack()

tk.Label(base, text=’緑’, bg=’green’, width=20).pack()

tk.Label(base, text=’青’, bg=’blue’, width=20).pack()

 


 

import tkinter as tk

base = tk.Tk()

topping = {0:’ノリ’, 1:’煮玉子’, 2:’もやし’, 3:’チャーシュー’}

check_value={}

for i in range(len(topping)):

              check_value[i] = tk.BooleanVar()

              tk.Checkbutton(base, variable=check_value[i], text = topping[i]).pack(anchor=tk.W)

 

def buy():

              for i in check_value:

                            if check_value[i].get() == True:

                                          print(topping[i])

 

tk.Button(base, text=’注文’, command=buy).pack()

 


 

import tkinter as tk

base = tk.Tk()

topping = {0:’ノリ’, 1:’煮玉子’, 2:’もやし’, 3:’チャーシュー’}

check_value={}

for i in range(len(topping)):

              check_value[i] = tk.BooleanVar()

              tk.Checkbutton(base, variable=check_value[i], text = topping[i]).pack(anchor=tk.W)

 

def buy():

              for i in check_value:

                            if check_value[i].get() == True:

                                          print(topping[i])

 

tk.Button(base, text=’注文’, command=buy).pack()

 


 

import tkinter as tk

base = tk.Tk()

radio_value = tk.IntVar()

radio_value.set(1)

lunch = {0:’Aランチ’,1:’Bランチ’,2:’Cランチ’}

tk.Radiobutton(text = lunch[0], variable = radio_value, value = 0).pack()

tk.Radiobutton(text = lunch[1], variable = radio_value, value = 1).pack()

tk.Radiobutton(text = lunch[2], variable = radio_value, value = 2).pack()

def buy():

              value = radio_value.get()

              print(lunch[value])

 

tk.Button(base, text=’注文’, command=buy).pack()

 


 

 

import tkinter as tk

import tkinter.messagebox as msg

base = tk.Tk()

base.withdraw()

response = msg.askyesno(‘大変!!!’, ‘大丈夫ですか?’)

 

if(response==True):

              print(‘大丈夫’);

else:

              print(‘大丈夫ではない’);

 


 

 

import tkinter as tk

base = tk.Tk()

string = tk.StringVar()

entry = tk.Entry(base, textvariable=string).pack()

label = tk.Label(base, textvariable=string).pack()

 


 

 

import tkinter as tk

base = tk.Tk()

def supermode():

              print(‘super mode!’)

 

menubar = tk.Menu(base)

filemenu = tk.Menu(menubar)

filemenu.add_command(label=’supermode’, command=supermode)

menubar.add_cascade(label=’Operation’, menu=filemenu)

base.config(menu=menubar)

 


 

 

import tkinter as tk

import tkinter.filedialog as fd

base = tk.Tk()

def open():

              filename = fd.askopenfilename()

              print(‘open file => ‘ + filename)

 

def exit():

              base.destroy()

 

def find():

              print(‘find ! ‘)

 

menubar = tk.Menu(base)

filemenu = tk.Menu(menubar)

menubar.add_cascade(label=’File’, menu=filemenu)

filemenu.add_command(label=’open’, command=open)

filemenu.add_separator()

filemenu.add_command(label=’exit’, command=exit)

editmenu = tk.Menu(menubar)

menubar.add_cascade(label=’Edit’, menu=editmenu)

editmenu.add_command(label=’find’, command=find)

base.config(menu=menubar)

 



 

 

7-2

【Windows】

pip install qrcode

 

【Mac】

pip3 install qrcode

 


 

 

import qrcode

encode_text = ‘http://google.com’

img = qrcode.make(encode_text)

type(img)

img.show()

 


 

python qrcode.py

 

【qrcode.pyの内容】

import qrcode as qr

import tkinter as tk

import tkinter.filedialog as fd

from PIL import ImageTk

base = tk.Tk()

base.title(‘QRcode Generator’)

input_area = tk.Frame(base, relief=tk.RAISED, bd=2)

image_area = tk.Frame(base, relief=tk.SUNKEN, bd=2)

encode_text = tk.StringVar()

entry = tk.Entry(input_area, textvariable=encode_text).pack(side=tk.LEFT)

qr_label = tk.Label(image_area)

def generate():

              qr_label.qr_img = qr.make(encode_text.get())

              img_width, img_height = qr_label.qr_img.size

              qr_label.tk_img = ImageTk.PhotoImage(qr_label.qr_img.size)

              qr_label.config(image=qr_label.tk_img,width=img_width,height=img_height)

              qr_label.pack()

encode_button = tk.Button(input_area,text=’QRcode!’,command=generate).pack(side=tk.LEFT)

input_area.pack(pady=5)

image_area.pack(padx=3, pady=1)

def save():

              filename = fd.asksaveasfilename(title=’名前をつけて保存する’, initialfile=’qrcode.png’)

              if filename and hasattr(qr_label, ‘qr_img’):

                            qr_label.qr_img.save(filename)

 

def exit():

              base.destroy()

 

menubar = tk.Menu(base)

filemenu = tk.Menu(menubar)

menubar.add_cascade(label=’File’, menu=filemenu)

filemenu.add_command(label=’save’, command=save)

filemenu.add_separator()

filemenu.add_command(label=’exit’, command=exit)

base.config(menu=menubar)

base.mainloop()