分类: Python

  • tkinter canvas

    from tkinter import *
    import random
    import tkinter.colorchooser as cc
    c = cc.askcolor()
    
    tk = Tk()
    canvas = Canvas(tk, width=400, height=400,bg=c[1])
    canvas.pack()
    
    def random_rectangle(width, height,fill_color):
        x1 = random.randrange(width)
        y1 = random.randrange(height)
        x2 = x1 + random.randrange(width)
        y2 = y1 + random.randrange(height)
        canvas.create_rectangle(x1, y1, x2, y2,fill=fill_color)
    
    
    _color = [ 'green', 'red', 'blue', 'orange', 'yellow', 'pink', 'purple', 'violet','magenta','cyan']
    
    #Draw rectangle with filled color
    
    for x in range(0, 500):
        random_rectangle(400, 400,_color[random.randrange(len(_color))])
    
    #write text to canvas
    canvas.create_text(130, 120, text='Who rode around on a moose.', fill='red')
    canvas.create_text(150, 100, text='There once was a man from Toulouse',fill=c[1])
    canvas.create_text(150, 150, text='He said, "It\'s my curse,', font=('Times', 15))
    canvas.create_text(200, 200, text='But it could be worse,', font=('Helvetica', 20))
    canvas.create_text(220, 250, text='My cousin rides round', font=('Courier', 22))
    canvas.create_text(220, 300, text='on a goose."', font=('Courier', 30),fill="blue")
    
    #Canvas background picture
    my_image = PhotoImage(file='c:\\test.gif')
    canvas.create_image(0, 0, anchor=NW, image=myimage)
    
    ##random_rectangle(400, 400, 'green')
    ##random_rectangle(400, 400, 'red')
    ##random_rectangle(400, 400, 'blue')
    ##random_rectangle(400, 400, 'orange')
    ##random_rectangle(400, 400, 'yellow')
    ##random_rectangle(400, 400, 'pink')
    ##random_rectangle(400, 400, 'purple')
    ##random_rectangle(400, 400, 'violet')
    ##random_rectangle(400, 400, 'magenta')
    ##random_rectangle(400, 400, 'cyan')
  • Python文件写入

    ###write method 1
    data = ["dog","cat","kcock"]
    with  open('c:/users/liutz/key.dat','w') as f:
        f.write('I am wriyting data in binary file\n')
        f.write("let's write   another list\n ")
        for pet in data:
            f.write(pet+"\n")
    ###write method 2
    f= open('hello.txt','w',encoding='utf-8')
    f.write("I am a teacher\n")
    f.write("wellcome to Python World!\n")
    mylist = ['Apple','Orange','Banana']
    f.write(str(mylist))
    f.close()
    ###read file ###
    f= open('hello.txt','r',encoding='utf-8')
    lines = f.readlines()
    print(lines[0])
    print(lines[1])
    print(lines[2])
    print("---- read file------")
    for line in lines:
        print(line+'\n')
    
    f.close()
    
  • tkinter基本widegets

    from tkinter.messagebox import *
    from tkinter import *
    root = Tk()
    
    photo = PhotoImage(file="./snow.png")  #file:t图片路径
    imgLabel = Label(root,image=photo,text="初春的雪!")     #把图片整合到标签类中
    imgLabel.pack(side=RIGHT)           #自动对齐
    
    tl = "This is my window"
    root.geometry("1024x900")  #窗口大小
    root.title(tl)             #窗口题目
    
    original_background = root.cget("background")  #得到窗口背景色
    print(original_background)
    #root.configure(background=original_background)
    root.configure(background="yellow")  #设置窗口背景色
    data = StringVar()
    def action():
    	print("I am  a Button!")
    	root.title("Click Me!")
    	root.geometry("+220+150")
    	root.update()
    	bg = root.cget("background")
    	showinfo(bg)  #弹出信息窗口
    
    
    label = Label(root,text="It's me!")
    label.pack()
    btn = Button(root,text="Enter",command=action)
    btn.pack()
    ent = Entry(root,textvariable=data)
    ent.pack()
    chk1 = Checkbutton(root,text="电视")
    chk2 = Checkbutton(root,text="电脑")
    chk3 = Checkbutton(root,text="电吹风")
    chk1.pack()
    chk2.pack()
    chk3.pack()
    frm = Frame(root,bord=6)
    frm.pack(side="top")
    text = Text(frm,width=30,height=6,background="light blue")
    text.pack()
    im = Image("雪.jpg",imgtype="jpg")
    im.pack
    
    root.mainloop()
    
  • Python下载小说huo

    #import utilib
    import requests, os
    from bs4 import BeautifulSoup
    url = 'https://www.biquge.com.cn/book/23341/'
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'lxml')
    booktitle = soup.find('h1').text
    if not os.path.isdir(booktitle): # 判断当前文件夹下是否存在和小说名同名的文件夹
        os.makedirs(booktitle) # 若不存在,则创建小说同名文件夹
    dd = soup.find_all('dd')
    for i in range(len(dd)):
        if i < 30:
            title = dd[i].find('a').text
            chap_url = dd[i].find('a')['href']
            response1 = requests.get('https://www.biquge.com.cn' + chap_url)
            soup1 = BeautifulSoup(response1.content, 'lxml')
            text = soup1.find('div', id='content').text
            f = open(booktitle + '/' + title + '.txt', 'a+', encoding='utf-8')
            f.write(text)
            print("正在下载《 {} 》...... {} / {} ".format(title, i+1, len(dd)))
        else:
            break
    print('本次共下载 {} 章, 保存地址:{}'.format(i, os.getcwd() + '\\' + booktitle + '\\'))
  • python 类(class)

    class Staff:
    
        def __init__ (self, pPosition, pName, pPay):
            self.position = pPosition
            self.name = pName
            self.pay = pPay
            print('Creating Staff object')
        def __str__(self):
    
            return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)
    
        def calculatePay(self):
            prompt = '\nEnter number of hours worked for %s: ' %(self.name)
            hours = input(prompt)
            prompt = 'Enter the hourly rate for %s: ' %(self.name)
            hourlyRate = input(prompt)
            self.pay = int(hours)*int(hourlyRate)
            return self.pay
    
    if __name__ == "__main__":
        officeStaff1 = Staff('Basic', 'Yvonne', 0)
        print(officeStaff1)
        print(officeStaff1.calculatePay())
  • Python tkinter

    from tkinter import *
    #root = Tk()
    
    # Label(root, text="Username").grid(row=0, sticky=W)
    # Label(root, text="Passqord").grid(row=1, sticky=W)
    # Entry(root).grid(row=0, column=1, sticky=E)
    # Entry(root).grid(row=1, column=1, sticky=E)
    # Button(root, text="Login").grid(row=2, column=1,sticky=E)
    # root.mainloop()
    
    # pack using in windows
    # frame = Frame(root)
    # Label(frame, text="PACK DEMO of side and fill").pack()
    # Button(frame, text="A").pack(side=LEFT, fill=Y)
    # Button(frame, text="B").pack(side=TOP, fill=X)
    # Button(frame, text="C").pack(side=RIGHT, fill=NONE)
    # Button(frame, text="D").pack(side=TOP, fill=BOTH)
    # frame.pack()
    # Label(root, text="Pack demo of expand").pack()
    # Button(root, text="I do not expand").pack()
    # Button(root, text="I not fill x both I expand").pack(expand=1)
    # Button(root, text="I fill x and expand").pack(fill=X, expand=1)
    # root.mainloop()
    
    #Find&Replace Dialoge
    parent = Tk()
    parent.title("Find & Replace")
    
    Label(parent,text="Find:").grid(row=0,column=0,sticky="e")
    Entry(parent,width=60).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=9)
    
    Label(parent,text="Replace:").grid(row=1,column=0,sticky="e")
    Entry(parent).grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=9)
    
    Button(parent,text='Find').grid(row=0,column=10,sticky='e'+'w',padx=2,pady=2)
    Button(parent,text='Find All').grid(row=1,column=10,sticky='e'+'w',padx=2)
    Button(parent,text='Replace').grid(row=2,column=10,sticky='e'+'w',padx=2)
    Button(parent,text='Replace All').grid(row=3,column=10,sticky='e'+'w',padx=2)
    
    Checkbutton(parent,text='Macth all word only').grid(row=2,column=1,columnspan=4,sticky='w')
    Checkbutton(parent,text='Match Case').grid(row=3,column=1,columnspan=4,sticky='w')
    Checkbutton(parent,text='Wrap around').grid(row=4,column=1,columnspan=4,sticky='w')
    
    Label(parent,text='Direction').grid(row=2,column=6,sticky='w')
    Radiobutton(parent,text='UP',value=1).grid(row=3,column=6,columnspan=6,sticky='w')
    Radiobutton(parent,text='Down',value=1).grid(row=3,column=7,columnspan=6,sticky='w')
    parent.mainloop()
    
    注意:编程环境使用了 parent.mainloop(),程序才开始运行。
    
    
  • Python: sent emails with embedded images 发邮件

    
    to send emails with images you need to use MIMEMultipart, but the basic approach:
    import smtplib
    
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "subject"
    msg['From'] = from_addr
    msg['To'] = to_addr
    
    part = MIMEImage(open('/path/to/image', 'rb').read())
    
    s = smtplib.SMTP('localhost')
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()
    
    will produce an email with empty body and the image as an attachment.
    
    The better way, ie to have the image as part of the body of the email, requires to write an HTML body that refers to that image:
    
    import smtplib
    
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "subject
    msg['From'] = from_addr
    msg['To'] = to_addr
    
    text = MIMEText('<img src="cid:image1">', 'html')
    msg.attach(text)
    
    image = MIMEImage(open('/path/to/image', 'rb').read())
    
    # Define the image's ID as referenced in the HTML body above
    image.add_header('Content-ID', '<image1>')
    msg.attach(image)
    
    s = smtplib.SMTP('localhost')
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()
    
    The trick is to define an image with a specific Content-ID and make that the only item in an HTML body: now you have an email with contains that specific image as the only content of the body, embedded in it.
  • Python文件读写方法

    context='hello,world,hello1\nworld,hello2\nworld,hello,world3 \n'
    with open('hello.txt','w+') as f:
          f.write(context)
          for x in range(0,5,1):
                f.write(str(x)+",")
          f.close
    with open('hello.txt','r') as f:
          datas=f.readlines()
          for data in datas:
                print(data)