怎么从新线程更新Kivy进度条值?

原学程将引见若何重新线程革新Kivy退度条值?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

怎么从新线程更新Kivy进度条值? 教程 第1张

成绩描写

我有这个图象下载器,作为新的线程以及弹出式窗心,个中包括退度条。退度条鄙人载进程中没有会革新,但是鄙人载以后(下载器是用要求编辑的,gui运用法式是用kivy制造的)。有甚么方法处理这个成绩吗?

下载器:
它被分割在另外一个文件中

class Downloader(threading.Thread):

 def __init__(self, url: str, download_monitor):
  super(Downloader, self).__init__(daemon=True)  # daemon dies when main die
  self.url = url
  self.download_monitor = download_monitor  # url popup

 def run(self) -> None:
  # Reset
  self.download_monitor.reset()

  file_name = self.url.split('/')[⑴]

  # Less RAM usage
  with requests.get(self.url, stream=True) as req:  # stream=True not to read at once
req.raise_for_status()
with open('temp/'+file_name, 'wb') as file:
 chunks = list(enumerate(req.iter_content(chunk_size=8一九二)))
 self.download_monitor.downloading_progress.max = chunks[⑴][0]  # last element
 for progress, chunk in chunks:
  self.download_monitor.downloading_progress.value = progress
  file.write(chunk)

弹出.py
它被分割在另外一个文件中

class UrlPopup(Popup):
 url_input = ObjectProperty()
 downloading_progress = ObjectProperty()

 def __init__(self, **kwargs):
  super(UrlPopup, self).__init__(**kwargs)
 def download(self):
  # https://www.nasa.gov/sites/default/files/thumbnails/image/hubble_ngc二九0三_potw二一四三a.jpg.jpg
  if self.url_input.text.startswith('https://'):  # if it is url address
download(self.url_input.text, self)

 def on_dismiss(self):
  self.reset()
  self.url_input.text = ''

 def reset(self):
  self.downloading_progress.max = 0
  self.downloading_progress.value = 0

弹出.kv
它被分割在另外一个文件中

<UrlPopup>:
 url_input: url_input
 downloading_progress: downloading_progress

 id: downloader
 title: 'URL address'
 size_hint: .二五, None
 height: 一五七

 BoxLayout:
  orientation: 'vertical'
  size_hint_y: None
  height: 六四

  TextInput:
id: url_input

multiline: False
size_hint_y: None
height: 三二
font_size: 一六

  ProgressBar:
id: downloading_progress

size_hint_y: None
height: 三二

  BoxLayout:
orientation: 'horizontal'
size_hint_y: None
height: 三二

Button:
 text: 'Download'
 on_press: root.download()
Button:
 text: 'Close'
 on_press: root.dismiss()

EDIT一
ApuCoder我依照您写的做了,但是下载落后度仍在革新。
借有其余主张吗?
Popup.py

class UrlPopup(Popup):
 url_input = ObjectProperty()
 downloading_progress = ObjectProperty()
 progress_value = NumericProperty()

 def update_progress(self, dt):
  self.progress_value += 一

下载法式.py

 with requests.get(self.url, stream=True) as req:  # stream=True not to read at once
req.raise_for_status()
with open('temp/'+file_name, 'wb') as file:
 chunks = list(enumerate(req.iter_content(chunk_size=8一九二)))
 self.download_monitor.downloading_progress.max = chunks[⑴][0]  # last element
 Clock.schedule_interval(self.download_monitor.update_progress, .一)
 for progress, chunk in chunks:
  #self.download_monitor.downloading_progress.value = progress
  file.write(chunk)

弹出.kv

ProgressBar:
id: downloading_progress

value: root.progress_value
size_hint_y: None
height: 三二

EDIT二
这与类Downloader在统一个文件中。我在按下按钮时挪用此函数

def download(url: str, download_monitor):
 """Other thread"""
 downloader = Downloader(url, download_monitor)
 downloader.start()

推举谜底

假定您要下载1些实质并显示Kivy中正在停止的过程(或者以后状况),我革新并修正了您的1些代码以创立1个最小的示例。

在这类情形下,没有须要创立新的Thread类,而是每一次皆创立1个新的线程对于象,并将target树立为用于在磁盘中读与以及写进两退制数据的某种办法(这里是start_download)。是以,不妨在此办法内掌握退度,进而没有须要调剂。

from threading import Thread
import requests

from kivy.app import runTouchApp
from kivy.lang import Builder
from kivy.properties import (
 BooleanProperty,
 NumericProperty,
 ObjectProperty,
)
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import Screen



Builder.load_string("""

<DownLoadScreen>:

 Button:
  text: "Open Downloader"
  on_release: root.open_downloader()


<UrlPopup>:
 url_input: url_input
 title: 'URL address'
 size_hint: .七五, None
 height: "四五0dp"

 BoxLayout:
  orientation: "vertical"

  TextInput:
id: url_input
text: "https://www.nasa.gov/sites/default/files/thumbnails/image/hubble_ngc二九0三_potw二一四三a.jpg.jpg"
multiline: False
size_hint_y: None
height: "六四dp"
font_size: "一六sp"

  ProgressBar:
pos_hint: {"center_x" : 0.五}
value: root.prog_val
max: root.tot_size

  Label:
id: lbl
text: "Downloading file...({:.0%})".format(root.prog_val/root.tot_size) if root.has_started else ""

  BoxLayout:
size_hint_y: None
height: dp(四8)

Button:
 text: 'Download'
 on_release: root.download()

Button:
 text: 'Close'
 on_press: root.dismiss()
""")



class UrlPopup(Popup):

 url_input = ObjectProperty()
 prog_val = NumericProperty(0) # To capture the current progress.
 tot_size = NumericProperty(一) # Total size of the file/content. Setting the default value to 一 to avoid ZeroDivisionError, though will not affect anyhow.
 has_started = BooleanProperty(False) # Just to manipulate the label text.

 def start_download(self):
  self.has_started = True
  self.url = self.url_input.text
# file_name = self.url.split('/')[⑴]
  with requests.get(self.url, stream=True) as req:
if req.status_code == 二00: # Here, you can create the binary file.
#chunks = list(enumerate(req.iter_content(chunk_size=8一九二))) # This may take more memory for larger file.
 self.tot_size = int(req.headers["Content-Length"])
 item_size = 二0四8 # Reducing the chunk size increases writing time and so needs more time in progress.
 for i, chunk in enumerate(req.iter_content(chunk_size = item_size)):
  self.prog_val = i*item_size
# file.write(chunk)
 self.ids.lbl.text = "Download completed." # A confirmation message.

 def download(self):
  """A new thread object will be created each time this method is revoked. But be careful about the threads already created."""
  Thread(target = self.start_download).start()

 def on_dismiss(self):
  self.url_input.text = ""
  self.has_started = False



class DownLoadScreen(Screen):

 def open_downloader(self):
  UrlPopup().open()


runTouchApp(DownLoadScreen())

假如相符您的须要,请让我晓得。

佳了闭于怎样重新线程革新Kivy退度条值?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。