Water tank system and mass conservation

Road to a Chemical Engineer: #1


Recap


 In last article, we have covered two things. First, what is Chemical engineering about, and second, the conservation law. If you remember the conservation law for instantaneous time, correctly, it is the followings:

RateIn-RateOut+RateGenerated-RateConsumed=RateAccumulated

 However, this article is not just about any conservation but "mass conservation". It is, literally, the conservation law applied upon mass. So, in mass conservation, the conservation law can be simply rewritten as follows:

RateMass In-RateMass Out+RateMass Generated-RateMass Consumed=RateMass Accumulated

 Now, we have the equation for mass conservation. Let's check this out with a realistic experiment.


Water tank system and mass conservation




 Imagine two water tanks. From one of the tank, water flows into another tank. Here is a mass conservation going on, right??

 Before we proceeding any further, we need to note that since only water is being used, mass conservation is equivalent to volume being conserved in this system. Let's say we use a common symbol of Q as a rate of volume flow.

 Without any calculation, you probably intuitively know that the volume of water went out from Tank A equals to the volume of water decreased from Tank A. However, using equation we derived above, makes this idea more clear. 

 So, in such situation for Tank A, there is no volume coming into the Tank A, so Q In = 0. That goes same for Generated = 0 and Q Consumed = 0 as there are nothing neither generated nor consumed here. Then, we are left out as following for Tank A:

-QOut = QAccumulated

 Isn't this something that we expected to happen??

 If you are to do this experiment to check the mass conservation for the water tank system, what would you do??

 One of the straightforward method is to measure the volume of water within the tank and measure the volume of water going out / into the tank. It is clear but it only tells you what it is. In other words, this does not expand into any other ideas or any other factors that may affect the result.

 So that, what if the initial water level in Tank A changes? What if now we use different pipes to allow the water flow?

 To answer these questions, the water tank system is now needed to be modeled with named variables for the conservation.


Modeling the water tank system

1. How does the rate of water flow determined??


  • What causes water to flow??


 Well, before anything, let's me ask you a question. What causes the water flow??

 You can actually answer this differently but the core concept is due to the pressure difference. Particularly, the pressure difference at the outlet in and out side.

 Why is this?? Just to note that, from here, it is something that engineers do not necessary have to know but since I researched from curiosity, I will share it here.

 Do you know the fluid flows from high to low pressure? This is actually something to do with what I learned in my secondary school (IB diploma Physics HL Option B). So, here, Bernoulli equation comes in. The Bernoulli equation states that:

12ρvx2+ρgzx+px= 12ρvy2+ρgzy+py

 We are not qualitatively analyze this equation. Yet, this still explains the water flow. Here, (ρgz + p) is basically the pressure, which means that having the pressure difference means this value differ at x and y. Then, what should be different between x and y to equate as in Bernoulli equation?

 The only variable there is the water speed, and if you think about the outlet, speed at the inside is 0, so there should be some speed of water at y. Thus, water flows out!!! I hope this make sense to you.

  • How to quantify the rate of water flow?



 To find the pressure difference, we need to find the pressure at each point of outlet. First, at the surface of the water of pipe is really straightforward, and that is just atmospheric pressure (patm). 

 How about at just inside of the outlet. To consider this, just to let you know that at the same level, the pressure is same. And, that is basically because there is same mass of water per area is upon such level. The pressure, here, can be given to be hydrostatic pressure (phydrostatic) + patm.

 phydrostatic can be given thought out simply using the high school physics equations. Mass at gravitational acceleration is falling upon a level per area, i.e. phydrostatic = ρgh.

 Then, the pressure difference at the outlet can be written as:

Pressure difference (P) = (patm+phydrostatic)-(patm)=ρgh

 Since this pressure difference is driving the water flow, we call this "Driving Force (DF)". Now how do we get the flow rate of water from this value??

 To get the flow rate, we need an another equation: 

Flow rate (Q) =Driving Force (DF)Resistance (R)

 This equation may not be familiar but I am sure that you know it from your Physics class. Do you remember I = V / R, where I is the current, or in other words, flow rate of charges, and V for potential difference and R for resistance. The same concepts lies here.

 So, flow rate of water can be given as follows:

Q=PR=ρghR

  • What is the resistance here??

 Now, we have managed to integrate the rate of water flow into variables. Let's go father by looking at what Resistance could be.

 To find it out, to simply use Hagen-Poiseuille equation:

Q=πr48ηLP

where r is the radius of the pipe, η is the viscosity of fluid (water),

 and L is the length of the pipe


You may have realized that this is somewhat similar to the equation we got in the previous section. The only difference is 1 / R and  (πr4) / (8ηL), and this is why we can equate them as to give resistance to be:

R=8ηLπr4

 Let's think about this intuitively. What happens if the length of the pipe increases? You can imagine more surface friction to be against the water flows, and therefore, the resistance increases. That agrees with the equation above!

 What about if the radius of the pipe increases? There will be more area of the pipe for the water to flow, so the resistance should decreases, right? And, this also agrees with the equation we have just got!!


  • Lastly... what is the rate of flow of water??
 Did you realize that we can now determine the Q Out differently without measure the volume of the water??

 This is just a combination of equations we have derived (partially):

QOut=πr48ηLρgh

 This equation itself is not too important as it is just a mix of concepts. However, what this implies is quite significant. That is the fact which height (h) being the only variable to determine the water flow rate. All symbols in (ρgπr4) / (8ηL) are constant in one water tank system.

 Hence, without weighting the water tank, with just the height, we now know that we can determine the water flow rate!!!


2. How else can accumulated water flow rate be written??


 Now we manage to write the rate of water flow out from Tank 1 in terms of more general way. We also know that it can be determined using height.

 Well, in that case, it would be great if we can also define Q Accumulated in terms of height. This is actually not too hard. Look at the followings:

-hρgR=Adhdt


 Does this make sense to you?? Area of water tank does not change, so rate of volume of water change can also be thought as area times the rate of water level change.



3. How can the conservation law be expressed for water tank system??


 Now, let's look back to the conservation equation derived above for Tank A:


-QOut = QAccumulated

 I suppose you know a different way of expressing the flow rates in terms of height of water level.


-hρg(πr48ηL)=Adhdt

or, just simply as:

-hρgR=Adhdt

 However, what is so good about being able to express this way?? Previous equation looked much simpler.


 Yet, I think you will understand if you think about doing such water tank system experiment. Which will be easier and more accurate: measuring the volume or measuring the height??

 I guess it is clear that it is much easier to find the change in height over time. One method of taking could be just filming the experiment and analyze the video later. However, volume cannot be measured in such way. You need to read out the volume, which is likely to be ambiguous, every few seconds.

 Thus, this equation is useful in experimental analysis. 

 Moreover, this new equation is useful as it consists different variables. So, it is possible to determine how the each variable can affect the rate of change in height, etc. 


Analyze the model obtained


 This is not it. Did you thought about integrating the equation we have obtained?? Let's see what we will get. 


hh0=e-(ρgAR)t
where h = h0 at t = 0

 This result is quite useful because the usefulness and the beauty of this equation can be illustrated by drawing this graph.



 This indicates that over time, the h will eventually reach a point where no more flow occurs. And, that is indeed true because as I mentioned previously, the pressure difference reaches 0 when the pressure difference at the outlet inside and outside equates (i.e. water level reaches the outlet level).



End note

 I do understand that this article was neither well written nor well explained but I hope you got a grasp something about chemical engineering. In addition, first read might not make sense to you but over time over days, reading the same thing can create a meaning to you and sometimes that works for me.


 Here, you might have realized there are tons of equations coming up. Yet, I have to say that this is the chemical engineering. Despite the sound of "chem", in this basic state we have not even came across any chemical equation. It certainly will but not get misunderstood. Yet, I hope you have enjoyed chemical engineering and will enjoy this with me further.



Previous Article: What does Chemical engineers do??
Next Article: Water tanks "in series" and steady state

What does Chemical engineers do??


Road to a Chemical Engineer: #0


About


 I have been posting all the articles in Japanese but this is a different series that I will be writing in English. The language I learn this subject, Chemical engineering!! So, in this series, I will be learning Chemical engineering with you. 


 Before I begin anything, I just need to talk about my English. As you might have already picked it up, my English skills are not perfect. English is yet to be my first language. Many flaws in grammars with limited vocabularies. Yet, through this series, I hope my English writing skills will improve at the same time.

 So, if you find any severe flaws or any perfect words that describes better, please leave them down in the comments, so I can enhance this experience with you.





What is a Chemical engineer??


 What is Chemical engineering?? Have you been wondering what it is and came to this page?? Then, you have arrived to the right one!! So, what really is Chemical engineering??

 The first impression that many people have and is incorrect is mixing the ideas with Chemistry. I have to clearly state that this is totally different from Chemistry, despite the word "chemi" in both subjects.

 Before digging into this the difference between Chemical engineering and Chemistry, first I have to let you know the difference between engineering and natural science.  This is my way of differentiating two but I would say "Natural science is the world eyes and Engineering is the world hands". So, what does this mean??

 I said natural science is the world eyes because it is about looking into the world and knowing more about it. For example, in mathematics, they pursue complex problems and try to find out the ways to prove the world mathematically. Whereas, in physics, it looks at the world in terms of all the physical concepts to explains the phenomenons on the earth.

 However, that is not true for engineering. In engineering, learning about the reasoning behind the concepts is not the main theme. Rather, the use of the concepts is the theme of this subject. In other words, in extreme, we do not need to know why there is gravity pulling us down to the earth, but we need to know how to use the concepts to make scale to weight things.

 The reason for me saying that engineering is the world's hand lays exactly this idea. So that, engineering is about what to do with the concepts with those ideas you have. So, before specify the Chemistry and Chemical engineering, I have to say that natural science and engineering cannot lack one or another. Because natural science can prove it, engineering can use it. And, thanks to engineering using it, natural science can be useful for the people's lives.

 Okay, so we are finally to the idea of Chemistry and Chemical engineering. How are they different??

 Chemistry is a natural science subject that purses the chemical reactions and what is happening inside the small beaker. On the other hands, Chemical engineering uses those Chemicals in a larger scale, looking at what could happen in real life. So, general idea of people working in labs are mostly chemist. And, Chemical engineers are more often found in plants or factories, etc.


 Chemical engineers do quite a variety of jobs in: food, chemicals, oils, plastics, etc. It is pretty much everything, right?? Here, their mission is to create a system such that it can produce the product at a greater efficiency (time and costs) and with a greater amount.

 So now, we finally understand what Chemical engineering is about.



What is the core idea in Chemical engineering?


 Chemical engineering has a single core idea that we stick with it through out the study. And, that is "conservation law". You may have heard about it before in your secondary school. In Physics, you hear energy conservation, in Chemistry, you probably heard mass conservation.

 However, there are more and more. Mass, momentum, energy, ... . It is very big idea and inevitable idea for all subjects; yet, we can state in a single equation:

Conservation law:

(In - Out + Generated - Consumed) = Accumulated


 Does this make sense to you?? So, it is basically telling you that whatever went in or generated and did not come out or consumed, is accumulated inside. Isn't this simple??

 It is indeed simple. However, this is not all. Conservation laws occur all at the same time and the real world is really complex that it creates this simple equation, more complex and more complex.

 Just to also note that, this conservation law is often considered in terms of instantaneous rate rather than over period of time as it can be the rates give the specific value for the particular time. More useful results and more accessible input data.



Conservation law (instantaneous rate):


Rate In - Rate Out + Rate Generated - Rate Consumed = Rate Accumulated



Endnote


 I hope today you took a small but significant glance at what Chemical engineering is. There is more to dig into about this simple little law but I will leave it for the next time.

 Next, let's look into more specific conservation laws, mass conservation with examples. Thanks for reading!


Next Article: Water tank system and mass conservation

Tkinter の配置用メソッド .pack() .gird() .place()

 Python3 マスターへの道:その3


  第3回ということで、今回は、ウィンドウに何か(ウィジェット)を表示したい、のですが……実は、今のままでは、表示できません。まずは、ウィジェットの位置を指定するメソッドを学ぶ必要があるのです。

 ですが、何も表示しないで、位置が指定できるわけではありません。なので、今回は、tk.Lable() で作ったウィジェットを使いながら、配置する位置の指定の基本を学んでいきます。

 ウィジェットの詳しい使い方は、次回『Python3 マスターへの道:その4』で学んでいこうと思うので、ここでは、ウィジェットという表示するものとして、認識しておきます。

1    import tkinter as tk
2    
3    root = tk.Tk()
4    
5    widget = tk.Label()
6    # 今回の新要素
7    widget.pack()
8    widget.grid()
9    widget.place(x=Number, y=Number)
10
11   root.mainloop()

 その位置を指定するために、必要なのが、.pack() と .grid() そして .place() の3つのメソッドたちです。これらのメソッドの学習には、こちらのサイト(全体的)こちらのサイト(.pack() を特に)を参考にさせてもらいました。


ウィジェットの位置の指定するために


 .pack() メソッド


7    widget.pack()

 これが、一番基本的なウィジェットの位置を指定できる、メソッドです。とりあえず、表示したいなら、これをウィジェットを作った後に、書けばいいだけです。デフォルトだと、上の中央に表示されます。





 ですが、表示したい位置もありますし、大きさとかも変えたい時もあるかもしれません。そんな時のための、オプションが、いくつかあります。実際に使って、表示させてみます。

 .pack(fill = 'x', padx = 10, pady = 5) で出力!fill は、横いっぱい('x')、縦いっぱい('y')に、ウィジェットを広げるオプション。padx と pady は、外枠からの余白を表しています。



 .pack(ipadx = 10, ipady = 5) で出力した場合。ipadx と ipady は、内枠からの余白です。わかりにくいですが、一番最初の、.pack() のみの出力と見比べてもらうと、枠のより中央に位置している感覚ですかね。↓




 複数を連続させて、.pack(fill = 'x') で表示させてみると……↓



 縦一列に表示されます。これは、つまり、デフォルトが、side = 'top' であるということです。つまり、横一列に表示したいなら、side = 'left' とかっこの中に、入れるだけで、次のように表示できます。ちなみに、fill は縦('y')でも使えます。↓



 では、横と縦を組み合わせて表示することはできるのでしょうか? ということで、4つのウィジェットを順番に、side = 'top', 'top', 'left', 'top' で試してみます。狙っているのは、右半分が、上と下で分かれたような、配置なのですが……↓




 おぉ、うまくいって……↓



 ないんですね。top やleft はどちら側に寄せているか、ということで、順番によって、ウィンドウが配置できているわけではありません。なので、横や縦一列に一次元方向に、配置する際には便利なのですが、二次元となると、それができないのです。

 それでは、二次元で配置する際は、どうすれば良いのでしょうか? それが、次の .grid() メソッドです。


 .grid() メソッド


8    widget.grid()

 ということで、.grid() では、二次元で配置ができるのですが、まずは、基本的な使い方から。かっこに何も入力しないで、出力してみると、左上の角に表示されました。↓




 複数個のウィジェットを、同時に、.grid() で表示してみると……↓




 先ほどとそれほど変わらないことがわかります。先ほどと大きく見た目が異なるのは、fill のオプションが使われていないためです。実際にいうと、fill というオプションは、.grid() にはないのです。

その代わりに、sticky というオプションがあります。これは、余裕があれば、fill のように広げる役割があるのですが、今後使いながら、確認していきたいと思います。

 しかし、まだ .gird() の凄さは伝わっていないでしょう。grid の最も大きい特徴は、文字通り、ウィンドウで表示する位置を、格子状に選択することができるのです。

8'   widget.grid(row = Number, column = Number)

 このコードをみてもらえば変わると思いますが、ここでは、配置場所を、縦の列と横の列を指定して、表示しています。そのため、ウィジェット同士の位置関係をはっきりとさせることができるのです。

 それでは、先ほど、.pack() では、できなかった二次元配列をしてみましょう。


 四色を2x2で並べたい時には、それぞれ (0, 0) (1, 0) (0, 1) (1, 1) の順番で、.grid() メソッドを使っていきます。↓




 格子状のように、配置されていることがよくわかりますね。

 それでは、先ほど .pack() で失敗してしまった、横並びの最後の二つが、上下で分かれて表示するようにするには、どうすればいいのでしょうか?

 それには、また別のオプションが必要になります。いくつかの縦の列に表示する際には、rowspan を、横の列の場合は、columnspan を使います。使い方は、簡単。通常通り、row と column で選択する最初の枠を選択して、rowspan と columnspan で、その長さを選択します。

 例えば、次のコードを実行させると、狙った配置で表示できます。

1    import tkinter as tk
2    
3    root = tk.Tk()
4    root.title(".pack() practice")
5    
6    red = tk.Label(root, text = "red", bg = "red", fg = "white")
7    blue = tk.Label(root, text = "blue", bg = "blue", fg = "white")
8    green = tk.Label(root, text = "green", bg = "green")
9    yellow = tk.Label(root, text = "yellow", bg = "yellow")
10   
11   red.grid(row= 0, rowspan = 2, column = 0)
12   blue.grid(row = 1, rowspan = 2, column = 1)
13   green.grid(row = 0, column = 2)
14   yellow.grid(row = 1, column = 2)
15   
16   root.mainloop()




 まだまだ、オプションもあるのですが、今回は、あくまで確認程度に配置のためのメソッドを学んでいきます。それにして、.grid() が一番使いやすそうと、私は感じました。配置場所がはっきりしているので、.pack() よりも多少面倒ですが、確実です。


 .place() メソッド


 これまで、.pack() はウィンドの枠からの位置関係、.grid() はウィンドウの左上からの位置関係を用いて、表示してきました。ですが、ウィジェットを、ウィンドウの好きな場所に自由に表示させたい時には、面倒ですよね。

 ということで、.place() は狙ったところを確実に表示できるメソッドになります。

9    widget.place(x=Number, y=Number)

 このコードの場合は、それぞれ x 軸と y 軸方向に、ピクセル数を入れて、ウィンドウの狙ったいちに、表示できます。なので、二つのウィジェットを (x=10, y=20)、そして、(x=15, y=30) とすることで、次のように、部分的に重ねることもできます。↓




 また、絶対に、位置を設定しなければならないわけではなくて、相対的な位置に配置するオプションもあるみたいです。ですが、今回は、あくまで、さらっと確認。また、.place() メソッドは多用するようでは、まだなさそうなので、これで .place() メソッドについては、終わりです。


最後に


 このように、.pack() と .grid() そして .place() の三つの配置メソッドを学んでいきました。色々な配置の仕方がわかって、楽しんじゃいましたね。ですが、まだ現時点では、意味もない、文字列を表示させているだけ。

 ですが、まだまだウィジェットの種類はあります。なので、次回は、他のウィジェットを学びながら、色々と配置していけたらいいです。

 また、今回は、画像多いため、重くなったり、わかりにくかったりした場合はすみません。コードを打っている私はまだしも、説明が難しいですね。これからも頑張ります。


前回:Tkinter のウィンドウをカスタマイズする方法

次回:tk.Label と tk.Button で画像を表示する

Tkinter のウィンドウをカスタマイズする方法


Python3 マスターへの道:その2

 

Tkinter のウィンドウをカスタマイズする


 前回は、Tkinter をインポートして、ウィンドウを表示するところまで、学習しました。しかし、そのウィンドウは未だ空白、少しずつカスタマイズしていきたいところです。ということで、今回は、空白のウィンドウのカスタマイズして行きたいと思います。

1    import tkinter as tk
2    
3    root = tk.Tk()
4    
5    # 今回の新要素
6    root.title("New Title")
7    root.geometry("NumberxNumber+Number+Number")
8    root.minsize(width=Number, height=Number)
9    root.maxsize(width=Number, height=Number)
10   root.resizable(width=Ture/False, height=Ture/False)
11      
12   root.mainloop()

 今回の新要素は、.title() と .geometry()、.minsize()、.maxsize()、そして .resizable()という、5つのメソッドです。これらによって、ウィンドウがどのように表示されるのかをプログラミングしていくことができるのです。


新メソッド: .title()


6    root.title("New Title")

 このメソッドは至ってシンプル。ウィンドウに名前をつけることができるようになります。そして、コードもシンプル。.title() のかっこの中に、つけたい名前を入れるだけ。絶対的な必要性はないかもしれませんが、わかりやすくする意味では、ささっとつけられるものになっています。

 このコードを実行すると、下のように出力されました。ちゃんと、ウィンドウの上に New Title になってますね。




新メソッド: .geometry()


ウィンドウの初期表示の大きさを設定


7'   root.geometry("NumberxNumber")
7'  root.geometry(width=Number, height=Number)

 このメソッドは、ウィンドウの初期表示の大きさを設定することができます。表示方法は上の二つ。どちらも出力は同じなので、1つ目の方が簡単に見えます。実際に、幅 x 高さ という形式で書いています。ですが、初見の人からしてみれば、2つ目は、幅と高さが一目でわかりますね。どちらで書きたいかは自分次第ってことですね。

 このコードを実際に、幅=300 pixel、高さ=500 pixel で実行してみると、しっかりと、下のように縦長のウィンドウが表示されましたね。




 ちなみに、二つ目の省略された方法で実行してみたら、高さと幅の順番が逆で、横長のウィンドウが……最初は面倒がらずに、一つ目の形式の方のように明白に表記した方がいいのかもしれません。


ウィンドウの初期表示の位置を設定


7''   root.geometry("+Number+Number")

 .geometry のメソッドは、ウィンドウの初期表示の位置を設定することもできます。そして、その方法は、パソコンの画面の左上からの距離(pixel)で表示されます。そして、数字の順番は、1つ目の数字は、画面の左からの距離、2つ目の数字は、画面の上からの距離になっています。

 ここで、マイナス(-)でも試したのですが、プラス(+)と同じように表示されました。また、Mac を使っているのですが、"+0+0" のように設定しても上のバーに被らないように表示されたので、上の一番角に表示することはできないようです。

 コードのカッコの中を (+300+600) のようにして、出力してみました。








※ウィンドウが見やすいように壁紙を変更しました。

 ここで、一つお願いです。初期表示の大きさを表示した際のように、明白に表示する方法がわからなかったので、一つしか表示してません。なので、知っている方はコメントください。


初期表示の大きさと位置を同時に設定


7    root.geometry("NumberxNumber+Number+Number")

 そして、二つを .geometry の二つの機能を組み合わせるようにして、上記のように表示できます。そして、カッコ内を (300x100+300+600) のようにして、実行してみると、先ほどのウィンドウの位置に、横長のウィンドウが表示されました。




新メソッド: .minsize() と .maxsize()


8    root.minsize(width=Number, height=Number)
8'   root.minsize("NumberxNumber")
9    root.maxsize(width=Number, height=Number)
9'   root.maxsize("NumberxNumber")

 そして、次のメソッドは、ユーザーがウィンドの大きさを変えることができる範囲を設定するものです。.minsize() で最小の大きさを、.maxsize() で最大の大きさを設定しています。これは、画像で表すのは難しいので、試してみるとわかります。

 これも、.geometry() のメソッドのように表記を二つの方法でできるので、基本を覚えておけば、すぐに使えます。ウィンドウ内で、大きさが小さすぎると問題がある際などに使うことになりそうですね。

 ここで、ユーザーが全くウィンドウの大きさを変えることができないようにするには、.geometry() で設定した幅と高さを、.minsize() と .maxsize() に設定すれば大丈夫そうです。しかし、面倒ですよね。そのために、次のメソッドがあります。


新メソッド: .resizable()


10   root.resizable(width=Ture/False, height=Ture/False)
10'  root.resizable(0/1, 0/1)

 そして、今回の最後の新しいメソッド、.resizable() です。これは、ユーザーがウィンドウの大きさを変更できないように設定することができます。そして、それは、False または 0 と設定することで、できます。ここでも、二つの表記がありますね。

 ですが、ここでは、2つ目の表記をした際に、どちらかの数字に 1 または True が含まれると、その方向のみに大きさが変更できるようになるのではなく、全体のウィンドウ自体の大きさが変えることができるようになってしまいます。

 なので、一方向のみの大きさを変えることを許可する場合は、先ほどのメソッドを使うしかなさそうです……

 カッコ内をどちらも 0 に設定して実行してみると、下のように、Mac のウィンドウの大きさを画面いっぱいにする、緑色のボタンの色が消えていることがわかります。これで、大きさが変更できなくなりましたね。




最後に


 このように、今回はウィンドウの表示をカスタマイズするための、5つのメソッドを学ぶことができました。ですが、まだウィンドウの中は空白のまま。次回は、ウィンドウに何かを表示させれればいいなぁ、と思っています。


前回:Python のモジュールのインポートの異なる方法と使い分け

次回:Tkinter の配置用メソッド .pack() .gird() .place()

Python のモジュールのインポートの異なる方法と使い分け


Python 3 マスターへの道:その1


Tkinter でウィンドウを表示する


 まずは、プレイ環境に必要な将棋盤を作っていくところから始めたいと思います。もちろん、私には、何の前知識もないので、こちらのサイトを参考にさせてもらいました。Tkinter という python3 の標準ライブラリに存在するパッケージを使ってみたいと思います。

 Tkinter については公式ページで、少し勉強してから使っていこうと思います。公式ページには、参考になるウェブサイトなどが添付されているので、積極的に使っていきます。


モジュールのインポート


 そうして、Tkinter について読んでいたのですが、いきなり引っかかってしまいました。それは、モジュールのインポートの仕方の基本についてです。実は、そこには主に4つの方法がありました。それら違いは、こちらから学ばせてもらいました。

1    import tkinter 

 まずは、tkinter が個別の名前空間としてインポートされます。これは、つまり、tkinter のメソッドやクラスを呼び出す際に、tkinter.メソッドや tkinter.クラスといった形で呼び出します。

2    import tkinter as tk

 次の、2つ目は、1つ目と同じく、個別の名前空間にインポートされます。ですが、ここでは as を使用することで、毎回 tkinter.メソッドや tkinter.クラスと書く代わりに、tk.メソッドや tk.クラスという形で呼び出すことができるようになります。

 なので、名前の長いモジュールの際や、なんども繰り返されるモジュールを使用する場合は、省略した名前で表記することで、効率的にコードを書くことができるのです。

3    from tkinter import ttk

 ここまでは、モジュール全体をインポートする形式でした。しかし、3つ目では、モジュールの中の特定のクラスやメソッドを呼び出す時に使用されます。また、1行目と2行目との大きな違いとして、個別の名前空間がないことが挙げられます。

 これは、つまり、既存していたクラスやメソッドと同一名のものがインポートされる時、それらは上書きされてしまうのです。

 しかし、利点として、tkinter.メソッドや tkinter.クラスのように、宣言しなくてよくなることが挙げられます。また、tkinter のライブラリの中から、どれが必要なのかをわかりやくすできることのようです。

4    from tkinter import *

 そして、4行目は、3行目の発展型で、ここでも、個別の名前空間が存在しないために、上書きが行われます。しかし、この場合は、モジュール全体を1行目や2行目のようにインポートしています。ですが、これは何が上書きされてしまったのか、把握が難しく、エラーを起こしやすいため、推奨しない場合が多いようです。

 ですが、色々、Tkinter の初心者向けのサイトを見てみると、4行目のように、インポートしている場合が、多いです。ですが、私は、推奨通りに、2行目の形式でインポートして行きたいと思います。

Tkinter のウィンドウを表示する


 それでは、まずは、Tkinter のウィンドウを表示するところから始めて行きます。コードは以下を使用しました。

1    import tkinter as tk
2    
3    root = tk.Tk()
4    root.mainloop()

 白紙のウィンドウが表示されました!



 結構シンプルにできました。ここでは、root というオブジェクトにTk クラスを割り当てています。そして、最後の .mainloop() は Tk クラスのメソッドを呼び出してます。この .mainloop() というメソッドは、イベントループと呼ばれるようです。イベントと処理を繰り返しているようで、真っ白の画面ですが、何からのイベントを待っているということになりますね。

 ですが、今回のウィンドウは形だけなので何も起こりません。今回は、ウィンドウを普通に閉じましたが、これからプログラムの中で、終了させたい際には、.destroy() というメソッドを使うことは覚えておかないといけないですね。

最後に


 今回は、インポートに時間をかけてしまって、全くと言っていいほど進展がありませんでした。それでも、コツコツ頑張って行きます。次回は、ウィンドウで何らかの表示を行うところまで行きたいですね。

 間違っている箇所や参考になった箇所があれば、コメントください!

※その6以降は、GUI を諸事情により、Tkinter から Kivy に移行しました。しかし、その5までの知識をある程度、ベースにはしているので、移行後はハイテンポで進んでいくと思います。なので、GUI の基本を知りたい方は、このまま読み進めてください。



前回:Python 脱初心者のために

次回:Tkinter のウィンドウをカスタマイズする方法

Python 脱初心者のために


Python 3 マスターへの道:その0










引用元: Python Software Foundation

はじめに


 本ブログ、最初の記事は、python3 の学習シリーズについてです。大学では、次の学期に履修する予定なのですが、先に学んでおいた方が、今の流行に乗り遅れたくない! そんな思いで、python 3 を学んでいきたいと思います。


本シリーズの紹介


・現在の状況


 実は、私は完全な初心者ではありません。なぜなら、高校に入りたての際に、学んでみようと試みたことがあ流のです。そして、入出力や条件分岐、繰り返しなどはできるようになっていました。しかし、それらは実際に、頑張れば1日で学べる程度のもので、初心者からの脱却には至りませんでした。

 その時は、リストやクラスに道を阻まれ、さらに、例外処理という壁を理由に、私は python 3 を一度断念しました。また、当時は、目標と目的が欠けていました。一通り学ぶには学んだのだが、その先何をすれば良いのかがわからなかったのです。好きなプログラムを作って、練習を積めと言われても……

 ということで、本シリーズでは、ある程度の目標を立て、それを目指して、一歩ずつ学んでいきたいと思っています。



・本シリーズの趣旨


 本シリーズの最初の目標として、非公式『どうぶつしょうぎ』のプレイ環境を python3 で再現してみたいと思います。そして、その後には、python3 の画像分析やデータ分析だけでなく、最終的には、機械学習、特にディープラーニング、にまで手を出せればと、雲を摑むような目標もあるのです。


・実行環境


 ちなみに、私の python 3 の実行環境は Mac での Jupyter notebook です。Jupyter notebook は、すぐにプログラムを実行できるので、学習には向いているのでは、と思っています。

 Anaconda からも、インストールできるのですが、別の方法でインストールしました。こちらのサイトがわかりやすく説明しているので、Mac に Jupyter notebook をインストールしたい方は、参考にしてみてください。


最後に


 私と同じように、躓いてしまった経験のある方、経験が豊富で応援しようという方、全く python3 を知らないけどなんとなく興味があり初めてみたい方、様々な人に読んでもらえる内容にしていきたいと思っています。

次回:Python のモジュールのインポートの異なる方法と使い分け