How to suspend a command without disturbing commands that are active

2

I would like to know if you know a command in python that suspends the operation of a command (for a few seconds) without disrupting the other commands that are active, since I wanted to make a rental system but time.sleep the other commands work. here is an example:

import time
aluguel=False
dinheiro=0
while True:
    time.sleep(10)
    aluguel=True
    dinheiro=dinheiro-1
    #o time.sleep inpede o funcionamento do codigo a seguir mas n quero que isso aconteça
a=str(input(''))
if a == MONEY:
    dinheiro=dinheiro+1'
    
asked by anonymous 02.11.2017 / 01:19

1 answer

1

So - "normal" programs at this level of learning are always executed with one instruction after another.

If you want one part of your code to do one thing while another part of your code does another, you need to have "something" that controls which part of the program is going to be executed, and how the processing will move to another while the first one is "paused".

The first thing that comes to everyone's head when you mention this is the concept of "threads". A "thread" is like a separate program, running in the same code, and in the same variables. You could have a thread running code from one function, while another thread runs code in another function. In this case, the time.sleep would have the effect you expect in the question: that thread stops, and the other thread continues execution.

However threads are far from being didactic: one has to really get a sense of the program flow and several other things to do something with direct threads work.

In your code, we can see that you do not use functions. If you have not yet mastered the use of functions to the point of being trivial, you do not really have any alternatives - why even thinking about this "pause" gets complicated. Where the program "goes" if part of the code is "paused". Where does he "come back"? In addition to everything that is described for them, functions serve as units of code organization to "know" which part is running. (To create a thread, for example, you pass a function as a parameter, as the starting point of the "secondary program" of that thread.)

So go, and learn about functions, and how the within variables of a function are "watertight" - are not visible or changeable outside the function, and how you can have "global" variables that are shared.

After that you will be able to think in an organized way in parts of the code that run in parallel.

That's why I'm writing this answer. As I put it above, there must be "something" that manages which part of your code is running in parallel. But this thing need not necessarily be its own code controlling threads. The library for graphical interfaces that comes with Python - tkinter, can do this very well, taking care of all the complexity for you.

When you use a graphical library, your program generally declares all the functions, classes, and objects it will use, and transfers control of the program to the library. In the case of tkinter, you call the function mainloop , and this is typically the last line of your program. From there, the control passes to the graphical library, which will call functions and methods of your code, which you have configured in the above lines. For example, it can call a function that changes the overall vairável "balance" when the user clicks a button, or after passing a certain time interval for example.

The process would be the same with other graphic libraries, such as gtk + and Qt - what they have in common is that they manage the "what code runs when" part, which for users is the "common", as we grow with applications that have menus ready to be used, or web forms. And more importantly: always, always organize your code into functions, first of all!

Here is an example that looks similar to what you were trying to do, using the "tkinter" framework:

import tkinter


def adiciona(*args):
    saldo.set(saldo.get()  + int(valor.get()))
    mostra_saldo()

def mostra_saldo(*args):
    mensagem["text"] = ("Saldo atual: {}".format(saldo.get()))

def cobra_aluguel():
    saldo.set(int(saldo.get()) - 1)
    mostra_saldo()
    janela.after(2000, cobra_aluguel)

def constroi():
    # Essas variáveis globais estarão visíveis em todas as funções.
    global janela, mensagem, saldo, valor
    # como as outras funções não modificam as mesmas com o sinal de "=",
    # apenas chamando métodos, não precisam declara-las como globais também. 

    janela = tkinter.Tk()
    valor = tkinter.Variable()
    saldo = tkinter.Variable()
    mensagem = tkinter.Label(janela)
    texto = tkinter.Label(janela, text="Valor a receber:")
    entrada = tkinter.Entry(janela, textvariable=valor)
    # O parametro "command" indica a função chamada quando o botão 
    # for clicado:
    botao = tkinter.Button(janela, text="Adicionar", command=adiciona)

    # métodos para exibir controles na janela, da forma mais simples:
    # um abaixo do outro:
    mensagem.pack()
    texto.pack()
    entrada.pack()
    botao.pack()
    # Exbibe o saldo inicial
    saldo.set(0)
    mostra_saldo()
    # Cobra aluguel daqui 2000 milisegundos: 
    janela.after(2000, cobra_aluguel)

    # Transfere o controle do programa para o tkinter,
    # que vai chamar "cobra_aluguel" no intervalo de tempo 
    # e "adiciona"  quando o botao for pressionado
    tkinter.mainloop()

constroi()
    
02.11.2017 / 17:48