LoginSignup
15
19

More than 3 years have passed since last update.

【Python】Tkinterによる複数ウィンドウの作成

Last updated at Posted at 2020-01-01

はじめに

こんにちは。

この記事ではTkinterを用いた複数のウィンドウを作るためのソースが分かる記事となっています。
よろしくお願いします。

環境

  • Windows 10 home
  • Python 3.7.1

ソースコード

こちらが完成したソースコードになります。
ぜひ実行してみてください。

main.py
import tkinter as tk

class Application(tk.Frame):
  def __init__(self,master):
    super().__init__(master)
    self.pack()
    master.geometry("300x300")
    master.title("ベースウィンドウ")

    self.window = []
    self.user = []

    self.button = tk.Button(master,text="ウィンドウ作成",command=self.buttonClick,width=10)
    self.button.place(x=110, y=150)
    self.button.config(fg="black", bg="skyblue")

  def buttonClick(self):
    self.window.append(tk.Toplevel())
    self.user.append(User(self.window[len(self.window)-1],len(self.window)))

class User(tk.Frame):
  def __init__(self,master,num):
    super().__init__(master)
    self.pack()
    self.num = num
    master.geometry("300x300")
    master.title(str(self.num)+"つ目に作成されたウィンドウ")

    self.button = tk.Button(master,text="コンソール上での確認",command=self.buttonClick,width=20)
    self.button.place(x=70, y=150)
    self.button.config(fg="black", bg="pink")

  def buttonClick(self):
    print("こちらは"+str(self.num)+"つ目に作成されたウィンドウです。")

def main():
  win = tk.Tk()
  app = Application(win)
  app.mainloop()

if __name__ == '__main__':
  main()

実際の動作

このプログラムを実行してみると、まずベースウィンドウが表示されます。
次に、ベースウィンドウにあるボタンをクリックすると、新たなウィンドウが作成され、表示されます。
作られたウィンドウにあるボタンをクリックするとコンソール上に、このウィンドウが何個目に作成されたのかを表示してくれます。

ベースウィンドウにあるボタンをクリックすれば、いくつでも新たなウィンドウを作成することができますので、ぜひ試してみてください。

ここまで読んでいただき、ありがとうございました。

15
19
0

Register as a new user and use Qiita more conveniently

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