Reputation: 343
I want to see continuously changing value of label in tkinter window. But I'm not seeing any of it unless I make a keyboard interrupt in MS-CMD while running which shows me the latest assigned value to label. Plz tell me ..What's going on & what's the correct code ??
import random
from Tkinter import *
def server() :
while True:
x= random.random()
print x
asensor.set(x)
app=Tk()
app.title("Server")
app.geometry('400x300+200+100')
b1=Button(app,text="Start Server",width=12,height=2,command=server)
b1.pack()
asensor=StringVar()
l=Label(app,textvariable=asensor,height=3)
l.pack()
app.mainloop()
Upvotes: 0
Views: 444
Reputation: 16109
The function server
is called when you click the button, but that function contains an infinite loop. It just keep generating random numbers and sending these to asensor
. You are probably not seeing any of it because the server
function is run in the same thread as the GUI and it never gives the label a chance to update.
If you remove the while True
bit from your code, a new number will be generate each time you click the button. Is that what you wanted to do?
Edit after comment by OP:
I see. In that case your code should be changed as follows:
import random
from Tkinter import Tk, Button, Label, StringVar
def server():
x = random.random()
print x
asensor.set(x)
def slowmotion():
server()
app.after(500, slowmotion)
app = Tk()
app.title("Server")
app.geometry('400x300+200+100')
b1 = Button(app, text="Start Server", width=12, height=2, command=slowmotion)
b1.pack()
asensor = StringVar()
asensor.set('initial value')
l = Label(app, textvariable=asensor, height=3)
l.pack()
app.mainloop()
I also introduced a new function, slowmotion
, which does two things: 1) calls server
, which updates displays the value, and 2) schedules itself to be executed again in 500ms. slowmotion
is first ran when you first click the button.
The problem with your code was that it runs an infinite loop in the main GUI thread. This means once server
is running, the GUI will not stop and will not get a chance to display the text you asked it to display.
Upvotes: 1