Home > Enterprise >  How can I only accept user entry for a minute in tkinter window
How can I only accept user entry for a minute in tkinter window

Time:11-15

import time
from tkinter import *
from tkinter.ttk import *
window = Tk()
e = Entry(window, width=100)
e.pack()
player2 = ""

def get_text():
    e.config(state='disabled')
    player2 = e.get()
    return player2

Button(window, text="done", command=get_text).pack()

t = 60
for x in range(t):
    t = t -1
    time.sleep(1)

if t == 0:
    Label(window, text="Times up").pack()
    e.config(state='disabled')
    player2 = e.get()
Label(window, text=player2).pack()
window.mainloop()

Here is my code, but its not really working. I would like to create an entry and let user only enter words only for one minute, unless the button done is pressed then the entry value is stored in a variable called player2.

CodePudding user response:

Take a look at PEP8. To solve your question you need the after method of tkinter, everything else is discouraged. Also see why you need to seperate your construction from your geometry method. Also Why to avoid wildcard imports.

from tkinter import *

def get_text():
    e.config(state='disabled')
    my_label.configure(text=e.get())

def after_time():
    my_label.configure(text="Times up")#configure instead of new
    e.config(state='disabled')
    
window = Tk()

e = Entry(window, width=100)
e.pack()

my_button = Button(window, text="done", command=get_text)
my_button.pack()

my_label = Label(window, text='..waiting for username..') #seperate construction from geometry
my_label.pack()

window.after(1000, after_time) #after(ms,function)
window.mainloop()

CodePudding user response:

The following code will disable the inputfield within one minute:

from threading import Timer
def disable():
    Label(window, text="Times up").pack()
    e.config(state='disabled')
    player2 = e.get()
Timer(60,disable).start()

Do also not that returning player2 in your get_text() function won't do anything. You won't change the variable outside the function. You should save your label and use config to set its text.

CodePudding user response:

Modified your code a bit in order to do the same, hope this is what you were aiming to do.

import threading
from tkinter import *
from tkinter.ttk import *
window = Tk()
e = Entry(window, width=100)
e.pack()
player2 = ""

def get_text():
    e.config(state='disabled')
    global player2
    player2 = e.get()
    return player2

Button(window, text="done", command=get_text).pack()

def logic():
    global player2
    Label(window, text="Times up").pack()
    e.config(state='disabled')
    player2 = e.get()
threading.Timer(60.0, logic).start()

Label(window, text=player2).pack()
window.mainloop()

CodePudding user response:

You can use Tk().after

root = Tk()
root.after(1000, function)
# 1000 = 1 Second
  • Related