# Why doesn't this code work?

**URL:** <https://discuss.python.org/t/why-doesnt-this-code-work/57327>\
**Category:** Python Help\
**Created:** [July 4, 2024, 10:46am UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327 "2024-07-04T10:46:21Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 4, 2024, 10:46am UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/1 "2024-07-04T10:46:21Z")

</div>

I am using a Mac mini M1 with OS Sonoma and Python 3.12 with PySimpleGUI 5 and am coding a simple Lottery number generator.

When Run, the code below shows the window on the screen exactly as expected. However, when I click on a Radio button, nothing happens. Also when I click on Exit, nothing happens. To (inexperienced) me, it looks like a problem with the Event action and the “while True” statement.

Here is the window on the screen:  
 ![Lottery](https://us1.discourse-cdn.com/flex002/uploads/python1/original/3X/d/6/d6f14b9214e681e47eeaa5ac3e5cab72f41d79a3.png)

Here is the code:

```python
import PySimpleGUI as sg
from tkinter import messagebox
import random

sg.set_options(font='Helvetica 14')

global lottery, choiceList
lottery = " "
choicelist = []

def main():
    layout = [[sg.Text("Choose a lottery")],
                [sg.Radio('Lotto', group_id=1, enable_events=True, key='-LOTTO-')],
                [sg.Radio('Euro Millions', group_id=1, enable_events=True, key='-EURO-')],
                [sg.Button('Exit', key='-EXIT-')]
             ]

    window = sg.Window("Lottery Number Generator", layout)

    sg.main_sdk_help()

    while True: # Event Loop
        event, values = window.read()
        print(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
    
        elif event == sg.Radio('Lotto', 1):
            lottery = "Lotto"
            print(f"contents of L lottery var is {lottery}")
            # create an empty List variable to hold the 6 numbers
            choiceList = []
            for i in range(6):
                    choiceLotto = [(random.randint(1, 59))]
                    choiceList.append(choiceLotto)
                    choiceList.sort()
                    print(f"contents of Lotto choiceList is {choicelist}")
            sg.popup("Here are your Lotto numbers ", choiceList)

        elif event == sg.Radio('Euro Millions', 1):
          lottery = ('Euro Millions')
          print("E lottery = ", lottery)
          choiceEuro = []
          for i in range(5):
                    choiceEuro = [(random.randint(1, 50))]
                    choiceList.append[choiceEuro]
                    choiceList.sort()
                    print("contents of Euro choiceList is ", choiceList)
          for i in range(2):
                    choiceEuro = [(random.randint(1, 12))]
                    choiceList.append(choiceEuro)
          sg.popup("Here are your Euro Millions Lottery numbers ", choiceList)
                       
        window.close()
 
if __name__ == ' __main__':
    main()

```

Any help would be appreciated.

Neil

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 4, 2024, 10:53am UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/2 "2024-07-04T10:53:53Z")

</div>

> [@neilcamp](#):
>
> ```python
> sg.main_sdk_help()
> 
> ```

I guess it’s waiting here for you to close the [help window](https://docs.pysimplegui.com/en/latest/call_reference/tkinter/functions/main/#main_sdk_help) (maybe it’s offscreen or otherwise hidden), so the while loop never enters the picture.

> [@neilcamp](#):
>
> ```python
> def main():
> ...
> while True:
> event, values = window.read()
> print(event, values)
> if event == sg.WIN_CLOSED or event == 'Exit':
> break    
> elif event == sg.Radio('Lotto', 1):
> ...
> elif event == sg.Radio('Euro Millions', 1):
> ...
> window.close()
> 
> ```

This `window.close()` is inside the `while True:` loop, and there’s no condition guarding it. So if you did get into this loop, I would expect it to exit immediately the first time, after handling the first event (which is probably not any of the ones your program is interested in).

I strongly recommend that you choose a **consistent** indentation pattern so that you can more easily see the structure of the code, and use functions to break the code up into logical pieces (so that the `if`s and `elif`s and `else`s aren’t so far apart and you can see what’s going on). The amount of space you’re using right now is all over the place. [PEP 8](https://peps.python.org/pep-0008/) is the de facto community standard.

---

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 4, 2024, 12:41pm UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/3 "2024-07-04T12:41:18Z")

</div>

Hello Karl.  
Thanks for your quick reply. I meant to change sg.main\_sdk\_help() to a comment with a hash sign before posting, as I was just using it as a help facility to try to find out what my problem is. Sorry about that.  
As I am using MS Code editor I have a structured indenting system in place. (Copy and paste has distorted this here a bit.)  
“This `window.close()` is inside the `while True:` loop,” Thank you. I have moved it out to the def Main () function, but it still remains the same ( I have to close the running app with the x icon). I just can’t seem to get into the events to action them.  
Any other suggestions?

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 4, 2024, 3:27pm UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/4 "2024-07-04T15:27:48Z")

</div>

The next step is to start the actual debugging process. Putting `print` calls in the code as you’ve done can give useful information, but information is only useful when seen by someone who’s actively trying to understand it.

So.

What results are you getting from the `print`s? For example, do you ever see anything interesting from `print(event, values)`? (Do you see anything printed at all, to confirm that the code gets to this point?) How about the other `print`s? Are the `elif` cases entered in the situations where you expect?

My guess is that the values you compare `event` with are wrong, and that the code also needs to care about the `values`. I don’t know how to use that GUI library, but it looks very suspicious to me to compare `event` to some `sg.Radio` result, because it looks like calling `sg.Radio` is how you made the radio button in the first place. An event is not going to be equal to a widget, and constantly making new widgets is probably not good.

> [@neilcamp](#):
>
> As I am using MS Code editor I have a structured indenting system in place. (Copy and paste has distorted this here a bit.)

I guess you mean VS Code (Visual Studio Code).

One possible reason for getting this distortion is mixing spaces and tabs. It’s possible to make that work with extreme care, but it’s still a bad idea. Also, if you’re trying to format the code for posting by adding extra indentation, please don’t. Markdown may support that, but it’s much easier and more reliable to use code fences, as described [in the pinned thread](https://discuss.python.org/t/about-the-python-help-category/42).

---

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 4, 2024, 6:25pm UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/5 "2024-07-04T18:25:31Z")

</div>

Hi Karl

When I click the radio button Lotto my print shows in the terminal::  
-LOTTO- {‘-LOTTO-’: True, ‘-EURO-’: False}

If I click Euro Millions:  
-EURO- {‘-LOTTO-’: False, ‘-EURO-’: True}

If I click Exit :  
-EXIT- {‘-LOTTO-’: False, ‘-EURO-’: True}

The program never seems to reach the other print statements.

Hope this helps.

Neil

---

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 4, 2024, 6:51pm UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/6 "2024-07-04T18:51:41Z")

</div>

> [@kknechtel](#):
>
> My guess is that the values you compare `event` with are wrong,

So I had a look at this and you are right.  
I changed the line from  
elif event == sg.Radio(‘Lotto’, 1):  
to  
elif event == “-LOTTO-”:

The difference is that the second code uses the key (name of the widget) of -LOTTO- whereas the first didn’t.

and it worked. The lottery numbers appeared in the popup window.  
So I’m now working on the Euro code and will revert tomorrow.

Thanks for your help.  
Neil

---

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 5, 2024, 11:13am UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/7 "2024-07-05T11:13:01Z")

</div>

My program now works perfectly. Thank you very much Karl for taking the time and effort to help me to get it right.

Best  
Neil

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 5, 2024, 2:53pm UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/8 "2024-07-05T14:53:16Z")

</div>

Glad to hear it was as straightforward as I hoped. I really know nothing about PySimpleGUI (besides the [recent licensing debacle](https://discuss.python.org/t/_/48790)) - I just know _how to solve problems_. I hope I was able to impart some wisdom and that in the future you’ll be able to get that much further on your own. 🙂

---

<div class="post-metadata">

**Author:** ![neilcamp](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/neilcamp/32/19120_2.png) [@neilcamp](https://discuss.python.org/u/neilcamp)\
**Post date:** [July 7, 2024, 8:26am UTC](https://discuss.python.org/t/why-doesnt-this-code-work/57327/9 "2024-07-07T08:26:29Z")

</div>

Hi Karl

Thank you. Yes indeed you were able to impart some wisdom from which I learnt more. I am an 89 year old hobbyist (so have a free PySimple GUI licence) who decided to start learning Python on a Mac about 3 months ago to prevent the possible onslaught of altheimers. As an Accountant retiring 15 years ago I did some VB database programming but I have a lot to learn here. It is challenging but highly enjoyable as I am learning by doing small projects as well as with a Python course.

Your help is much appreciated.

Neil
