6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python] Tkinterで複数のWindowを表示

Posted at

#はじめに

Tkinterで複数のWindow画面を表示する方法を説明します。

#結果
Tkinterのクラス化のテンプレートを利用しました。
下記の手順で、コードを組み立てます。

  1. Window 1のためのWin1クラスを用意する。
  2. Window 2のためのWin2クラスを用意する。
  3. Win1クラスのCall back function(Buttonを押すときの動作)に、Windows 2を開ける動作を定義する。

bandicam-2020-05-11-11-46-00-975.gif

#プログラミングコード

import tkinter as tk
from tkinter import ttk

class Win1(tk.Frame):
    def __init__(self,master):
        super().__init__(master)
        self.pack()

        self.master.geometry("400x400")
        self.master.title("window 1")
        self.create_widgets()

    def create_widgets(self):
        # Button
        self.button_new_win = ttk.Button(self)
        self.button_new_win.configure(text="Open Window 2")
        self.button_new_win.configure(command = self.new_window)
        self.button_new_win.pack()

    #Call back function
    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Win2(self.newWindow)



class Win2(tk.Frame):
    def __init__(self,master):

        super().__init__(master)
        self.pack()
        self.master.geometry("300x300")
        self.master.title("window 2")
        self.create_widgets()

    def create_widgets(self):
        # Button
        self.button_quit = ttk.Button(self)
        self.button_quit.configure(text="Close Window 2")
        self.button_quit.configure(command=self.quit_window)
        self.button_quit.pack()

    def quit_window(self):
        self.master.destroy()


def main():
    root = tk.Tk()
    app = Win1(master=root)#Inherit
    app.mainloop()

if __name__ == "__main__":
    main()

#参考資料

  1. 【Python】Tkinterのテンプレート

2. Tkinter example code for multiple windows 

6
7
2

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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?