0

How to run both input() and buttons() at the same time? Preferably with no libraries.

from threading import*
from asyncio import*
from multiprocessing import*
from time import*
from tkinter import*

yhealth = 0

def onButton(n):
    global m
    if n == 0:
        return m
    else:
        m = n
        return n

def buttons():
    sleep(1)
    main = Tk()
    main.geometry('250x50')
    Att = Button(main, text = 'Attack', command = lambda:(onButton(1), main.destroy()), fg = 'red')
    Att.pack(side = LEFT)
    Reg = Button(main, text = 'Regen', command = lambda:(onButton(2), main.destroy()), fg = 'red')
    Reg.pack(side = LEFT)
    Rock = Button(main, text = 'Attack', command = lambda:(onButton(3), main.destroy()))
    Rock.pack(side = RIGHT)
    Shield = Button(main, text = 'Shield', command = lambda:(onButton(4), main.destroy()), fg = 'blue')
    Shield.pack(side = RIGHT)
    main.mainloop()

def inputchoose():
    global chosenmove
    chosenmove = 0
    chosenmove = int(input('Choose 1/2/3/4'))
    if chosenmove == (1 or 2 or 3 or 4):
        return chosenmove
    return(chosenmove)

def movetell():
    global yhealth
    ymove = 0
    inputchoose(), buttons() ##this part doesn't work, it waits for input to close, and only then turns on #buttons
    while True:
        if buttons() != None:
            ymove = str(buttons())
            print('lol')
            break
        if inputchoose() != None:
            print('lol.')
            ymove = str(inputchoose())
            break

#remaking the entire code in general would be nice as well, tysm

I've tried many variations, but none of it works, so I'm hopeless.

the name
  • 1
  • 2

1 Answers1

0

I understood that you want a keyboard input listener but have the buttons active at the same time as an alternative input.

input() will always block the thread, so if you want several threads you need to create them : https://docs.python.org/3/library/threading.html

You will find examples on SO searching for "python non-blocking input" (e.g. https://stackoverflow.com/a/57387909/2197181)

JulienD
  • 7,102
  • 9
  • 50
  • 84
  • unfortunately using Thread doesn't work with buttons as running buttons as a Thread makes them unusable, because they don't respond after pressing on them without making them block the entire thread. Input also doesn't work with Thread. Does that mean I have to go for the second link? – the name Jul 23 '23 at 09:58
  • The second link is an example of input working in a thread, so one of these statements must be wrong. – JulienD Jul 23 '23 at 10:00
  • Buttons already have a listener in their own thread, so you should not add one yourself. It is the kb input you have to wrap. – JulienD Jul 23 '23 at 10:02