Найти - Пользователи
Полная версия: Проблема с циклом
Начало » Python для новичков » Проблема с циклом
1
python335
Я хочу сделать с помощью tkinter так, чтобы при нажатии на кнопку в Label добавлялось одно ‘X’ кажд1ю секунду.
Вот как сделал:
 from tkinter import *
import time
root = Tk()
def cicle():
      global texter, oper
      for c in range(0, 10):
            texter = texter + 'X'
            oper["text"] = texter
            oper.pack(side='top', fill='x')
            time.sleep(1)
texter = 'X'
oper = Label(root, text=texter, width=3, height=1)
oper.pack(side='top', fill='x')
start = Button(root, text='Start', command=cicle)
start.pack(side='bottom', fill='x')
root.mainloop()
Но при попытке нажатия на кнопку - программа зависает и отвисает только по окончаню цикла, и появляется сразу 11-12 иксов. Как это можно исправить?
PEHDOM
честно говоря в ТК не силен, но как я понимаю тут дело не в цикле а в принципе работы Button-а(или mainloop ткинтера), вы не увидите результата нажатия пока процедура не отработает полностью и не вернет какойнибудь “финишед”… первое что приходит в голову это использовать threading
 from tkinter import *
import time
import threading
root = Tk()
def run():
    t1 = threading.Thread(target=cicle)
    t1.start()
def cicle():
      global texter, oper
      for c in range(0, 10):
            texter = texter + 'X'
            oper["text"] = texter
            #oper.pack(side='top', fill='x')
            time.sleep(1)
texter = 'X'
oper = Label(root, text=texter, width=3, height=1)
oper.pack(side='top', fill='x')
start = Button(root, text='Start', command=run)
start.pack(side='bottom', fill='x')
root.mainloop()
ХЗ может ктото предложит более элегантное решение без многопоточности..
PEHDOM
я лошара, все гораздо проще, ну и + я таки совсем плохо знаю ткинтер. код без многопоточности:
 from tkinter import *
import time
root = Tk()
def cicle():
      global texter, oper
      for c in range(0, 10):
            texter = texter + 'X'
            oper["text"] = texter
            #oper.pack(side='top', fill='x')
            oper.update()
            time.sleep(1)
texter = 'X'
oper = Label(root, text=texter, width=3, height=1)
oper.pack(side='top', fill='x')
start = Button(root, text='Start', command=cicle)
start.pack(side='bottom', fill='x')
root.mainloop()
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB