Quantcast
  • Login
    • Account
    • Sign Up
  • Home
    • About Us
    • Catalog
  • Search
  • Register RSS
  • Embed RSS
    • FAQ
    • Get Embed Code
    • Example: Default CSS
    • Example: Custom CSS
    • Example: Custom CSS per Embedding
  • Super RSS
    • Usage
    • View Latest
    • Create
  • Contact Us
    • Technical Support
    • Guest Posts/Articles
    • Report Violations
    • Google Warnings
    • Article Removal Requests
    • Channel Removal Requests
    • General Questions
    • DMCA Takedown Notice
  • RSSing>>
    • Collections:
    • RSSing
    • EDA
    • Intel
    • Mesothelioma
    • SAP
    • SEO
  • Latest
    • Articles
    • Channels
    • Super Channels
  • Popular
    • Articles
    • Pages
    • Channels
    • Super Channels
  • Top Rated
    • Articles
    • Pages
    • Channels
    • Super Channels
  • Trending
    • Articles
    • Pages
    • Channels
    • Super Channels
Switch Editions?
Cancel
Sharing:
Title:
URL:
Copy Share URL
English
RSSing>> Latest Popular Top Rated Trending
Channel: Python Archives - Mouse Vs Python
NSFW?
Claim
0


X Mark channel Not-Safe-For-Work? cancel confirm NSFW Votes: (0 votes)
X Are you the publisher? Claim or contact us about this channel.
X 0
Showing article 286 of 498 in channel 13308888
Channel Details:
  • Title: Python Archives - Mouse Vs Python
  • Channel Number: 13308888
  • Language: English
  • Registered On: May 15, 2013, 4:53 pm
  • Number of Articles: 498
  • Latest Snapshot: January 12, 2023, 3:22 pm
  • RSS URL: http://www.blog.pythonlibrary.org/category/python/feed
  • Publisher: https://www.blog.pythonlibrary.org/category/python/
  • Description: Where You Can Learn All About Python Programming
  • Catalog: //python288.rssing.com/catalog.php?indx=13308888
Remove ADS
Viewing all articles
Browse latest Browse all 498
↧

PySimpleGUI: Working with Multiple Windows

January 20, 2021, 7:06 am
≫ Next: PyDev of the Week: Leodanis Pozo Ramos
≪ Previous: PyDev of the Week: Claudia Regio
$
0
0

When you are creating graphical user interfaces (GUIs), you will often find that you need to create more than one window. In this tutorial, you will learn how to create two windows with PySimpleGUI.

PySimpleGUI is one of the easiest Python GUIs to get started with. It wraps other Python GUIs and gives them a common interface. You can read more about it in my Intro to PySimpleGUI or in my article for Real Python, PySimpleGUI: The Simple Way to Create a GUI With Python.

Getting Started

You will want to install PySimpleGUI to get started using it. You can use pip for that:

python -m pip install pysimplegui

Making a Window Modal

PySimpleGUI provides a Window Element that you use to display other Elements in, such as buttons, text, images, and more. These Windows can be made Modal. A Modal Window won’t let you interact with any other Windows in your program until you exit it. This is useful when you want to force the user to read something or ask the user a question. For example, a modal dialog might be used to ask the user if they really want to Exit your program or to display an end-user agreement (EULA) dialog.

You can create two Windows and show them both at the same time in PySimpleGUI like this:

import PySimpleGUI as sg

def open_window():
    layout = [[sg.Text("New Window", key="new")]]
    window = sg.Window("Second Window", layout, modal=True)
    choice = None
    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break
        
    window.close()


def main():
    layout = [[sg.Button("Open Window", key="open")]]
    window = sg.Window("Main Window", layout)
    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break
        if event == "open":
            open_window()
        
    window.close()


if __name__ == "__main__":
    main()

When you run this code, you will see a small Main Window that looks like this:

PySimpleGUI Main Window

If you click on the “Open Window” button, you will get a new Window that looks like this:

New Window in PySimpleGUI

This second window has a parameter named modal in it that is set to True. That means you cannot interact with the first Window until you close the second one.

Now let’s look at a way that you can shorten your code if you are creating a simple Window like the one above.

Creating a New Window In-Line

You don’t have to write a completely separate function for your secondary Window. If you’re not going to have a lot of widgets in the second Window, then you can create the Window as a one or two-liner.

Here is one way to do that:

import PySimpleGUI as sg


def main():
    layout = [[sg.Button("Open Window", key="open")]]
    window = sg.Window("Main Window", layout)
    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break
        if event == "open":
            if sg.Window("Other Window", [[sg.Text("Try Again?")], 
                                          [sg.Yes(), sg.No()]]).read(close=True)[0] == "Yes":
                print("User chose yes!")
            else:
                print("User chose no!")
        
    window.close()


if __name__ == "__main__":
    main()

In this example, when you click the “Open Window” button, it creates the secondary Window in a conditional statement. This Window calls read() directly and closes when the user chooses “Yes”, “No” or exits the Window. Depending on what the user chooses, the conditional will print out something different.

The Traditional Multiple Window Design Patter

PySimpleGUI has a recommended method for working with multiple windows. It is mentioned in their Cookbook and in their demos on Github. Here is an example from Demo_Design_Pattern_Multiple_Windows.py:

import PySimpleGUI as sg
"""
    Demo - 2 simultaneous windows using read_all_window

    Window 1 launches window 2
    BOTH remain active in parallel

    Both windows have buttons to launch popups.  The popups are "modal" and thus no other windows will be active

    Copyright 2020 PySimpleGUI.org
"""

def make_win1():
    layout = [[sg.Text('This is the FIRST WINDOW'), sg.Text('      ', k='-OUTPUT-')],
              [sg.Text('Click Popup anytime to see a modal popup')],
              [sg.Button('Launch 2nd Window'), sg.Button('Popup'), sg.Button('Exit')]]
    return sg.Window('Window Title', layout, location=(800,600), finalize=True)


def make_win2():
    layout = [[sg.Text('The second window')],
              [sg.Input(key='-IN-', enable_events=True)],
              [sg.Text(size=(25,1), k='-OUTPUT-')],
              [sg.Button('Erase'), sg.Button('Popup'), sg.Button('Exit')]]
    return sg.Window('Second Window', layout, finalize=True)

window1, window2 = make_win1(), None        # start off with 1 window open

while True:             # Event Loop
    window, event, values = sg.read_all_windows()
    if event == sg.WIN_CLOSED or event == 'Exit':
        window.close()
        if window == window2:       # if closing win 2, mark as closed
            window2 = None
        elif window == window1:     # if closing win 1, exit program
            break
    elif event == 'Popup':
        sg.popup('This is a BLOCKING popup','all windows remain inactive while popup active')
    elif event == 'Launch 2nd Window' and not window2:
        window2 = make_win2()
    elif event == '-IN-':
        window['-OUTPUT-'].update(f'You enetered {values["-IN-"]}')
    elif event == 'Erase':
        window['-OUTPUT-'].update('')
        window['-IN-'].update('')
window.close()

When you run this code, you can open up several different windows that look like this:

Multiple PySimpleGUI Windows

You will want to try out using both of these methods to see which works the best for you. The nice thing about this method is that you have only one event loop, which simplifies things.

Wrapping Up

PySimpleGUI lets you create simple as well as complex user interfaces. While it’s not covered here, you can also use sg.popup() to show a simpler dialog to the user. These dialogs are can be modal too but are not fully customizable like a regular Window is.

Give PySimpleGUI a try and see what you think.

Related Reading

  • A Brief Intro to PySimpleGUI
  • The Demos for PySimpleGUI
  • Real Python – PySimpleGUI: The Simple Way to Create a GUI With Python

The post PySimpleGUI: Working with Multiple Windows appeared first on Mouse Vs Python.

↧
Search

Remove ADS
Viewing all articles
Browse latest Browse all 498

Trending Articles


Practice Sheet of Right form of verbs for HSC Students

September 22, 2019, 11:40 pm

Download: FK ft Shenky – Nakuyewa ”Prod by: Shenky”

February 16, 2017, 4:24 pm

How to win at Markstrat (Markstrat Tips and Tricks) – Vodites

January 5, 2014, 10:34 pm

Ominde Commission Report and Recommendations – Ominde Report of 1964

March 16, 2015, 5:14 am

Bureau of Internal Revenue: Regional Offices (Directory)

January 9, 2014, 11:06 pm

GO 53 on Enhancement of Ex-gratia upto 5 Lakhs Toddy Tappers in Telangana

March 26, 2017, 11:23 pm

Cakewalk CA-2A Leveling Amplifier v2.0.1.97 WiN, v2.0.1.96 OSX Incl Keygen

October 17, 2016, 7:20 am

Mp3 Download: Mdu - Kunjenjenjena

December 7, 2017, 8:16 am

How the kill the job , when DTP request running for long hours.

July 26, 2013, 2:41 am

Microsoft Intune から展開しているアプリのアップデートについて

October 17, 2016, 4:11 am

18-year-old girl was beaten for half an hour by two Northampton men in 'an...

September 1, 2017, 10:00 pm

Car crash in Dunton Bassett leaves driver in critical condition

October 7, 2014, 7:51 am

Macky 2, Two Others In Road Accident

March 29, 2015, 5:34 am

Application log 00000000000000089514: Could not convert queue DLVST90CLNT

May 14, 2015, 11:27 pm

Detroit mafia: D’Anna Brothers agree to plea deal

April 21, 2016, 6:56 am

Delivery block field greyed out using VA02

January 26, 2016, 2:52 pm

Muloraki Au

June 22, 2016, 1:44 am

【個人撮影】スマホのプライベート映像♪「中に出さないで///」カラオケ屋での生ハメ撮りが流出w【リベンジポルノ】@PornHub

October 12, 2017, 2:23 pm

BREAKING NEWS: Diamond Platnumz Is Reported Dead After Ghastly Car Accident

February 9, 2018, 4:56 am

FIAT 500 B0111 B0112

July 5, 2018, 10:31 am

Search

  • RSSing>>
  • Latest
  • Popular
  • Top Rated
  • Trending
© 2025 //www.rssing.com