Python:单击按钮时创建新线程或进程

时间:2018-03-18 05:30:07

标签: python tkinter

在Python 3.6.4中,每次点击按钮时启动新的单独进程或线程的好方法是什么?我已经编写了这段代码,但它没有按照我想要的方式工作。

from multiprocessing import process 
import requests
import threading 
from tkinter import *

def download():
    name=entry2.get()
    url=entry1.get()

    r = requests.head(url)
    if name:
          file_name = name
    else:
          file_name = url.split('/')[-1]
    try:
          file_size = int(r.headers['content-length'])
          part=file_size/4
          start=0
          end=part
    except:
           print ("Invalid URL")
           return


    print ('%s downloaded' % file_name)


def thread(url):

    file_name=entry2.get()
    r=requests.get(url)
    data=r.content

    with open('file_name','rb+')as fp:
          data1=fp.read()

    with open('file_name',"wb+") as fp:
          data1=fp.write(data)

    print("its working3")

if __name__=='__main__':
    p=process(target=download,args=())
    p.start()
    p.join()

root=Tk()

frame=Frame(root,width=500,height=450,bg="lightpink")

url1=Label(frame,text="enter url here")
name=Label(frame,text="enter the name of the file")

url1.grid(row=0,sticky=E)
name.grid(row=1,sticky=E)

entry1=Entry(frame)
entry2=Entry(frame)

entry1.grid(row=0,column=1)
entry2.grid(row=1,column=1)

button1=Button(frame,text="download" ,command=download)        
button1.grid(row=2,column=0)
button3=Button(frame,text="quit",command=frame.quit)
button3.grid(row=2,column=1)
frame.grid()

print("its working4")

root.mainloop()

1 个答案:

答案 0 :(得分:0)

这可以胜任吗?它使用threading模块而不是multiprocessing

#from multiprocessing import process
from threading import Thread as process
import requests
import threading 
from tkinter import *

def download():
    name=entry2.get()
    url=entry1.get()

    r = requests.head(url)
    if name:
          file_name = name
    else:
          file_name = url.split('/')[-1]
    try:
          file_size = int(r.headers['content-length'])
          part=file_size/4
          start=0
          end=part
    except:
           print ("Invalid URL")
           return


    print ('%s downloaded' % file_name)


def thread(url):

    file_name=entry2.get()
    r=requests.get(url)
    data=r.content

    with open('file_name','rb+')as fp:
          data1=fp.read()

    with open('file_name',"wb+") as fp:
          data1=fp.write(data)

    print("its working3")

root=Tk()

frame=Frame(root,width=500,height=450,bg="lightpink")

url1=Label(frame,text="enter url here")
name=Label(frame,text="enter the name of the file")

url1.grid(row=0,sticky=E)
name.grid(row=1,sticky=E)

entry1=Entry(frame)
entry2=Entry(frame)

entry1.grid(row=0,column=1)
entry2.grid(row=1,column=1)

button1=Button(frame,text="download" ,command=lambda: process (target = download).start ())        
button1.grid(row=2,column=0)
button3=Button(frame,text="quit",command=root.destroy)
button3.grid(row=2,column=1)
frame.grid()

print("its working4")

root.mainloop()