1编写一个程序在窗口中显示一个Hello World!的标签。2编写一个程序在窗口中显示两个文本框和一个按钮。当用户单击按钮时程序应该将两个文本框中的内容相加并在标签中显示结果。3编写一个程序在窗口中显示一个列表框和一个按钮。当用户单击按钮时程序应该将选定的项从列表框中删除。4编写一个程序爬取百度贴吧中某个贴子的所有图片。5编写一个程序爬取新浪新闻的热门新闻标题和链接。写出注释
1.编写一个程序,在窗口中显示一个“Hello, World!”的标签。
import tkinter as tk
# 创建窗口
window = tk.Tk()
# 创建标签
label = tk.Label(window, text="Hello, World!")
# 将标签放置在窗口中
label.pack()
# 运行窗口
window.mainloop()
2.编写一个程序,在窗口中显示两个文本框和一个按钮。当用户单击按钮时,程序应该将两个文本框中的内容相加并在标签中显示结果。
import tkinter as tk
# 创建窗口
window = tk.Tk()
# 创建文本框
text1 = tk.Entry(window)
text2 = tk.Entry(window)
# 创建按钮
button = tk.Button(window, text="相加", command=lambda: add_numbers())
# 创建标签
label = tk.Label(window)
# 将文本框、按钮和标签放置在窗口中
text1.pack()
text2.pack()
button.pack()
label.pack()
# 定义按钮点击事件
def add_numbers():
num1 = int(text1.get())
num2 = int(text2.get())
result = num1 + num2
label.config(text="结果:" + str(result))
# 运行窗口
window.mainloop()
3.编写一个程序,在窗口中显示一个列表框和一个按钮。当用户单击按钮时,程序应该将选定的项从列表框中删除。
import tkinter as tk
# 创建窗口
window = tk.Tk()
# 创建列表框
listbox = tk.Listbox(window)
listbox.insert(tk.END, "选项1")
listbox.insert(tk.END, "选项2")
listbox.insert(tk.END, "选项3")
# 创建按钮
button = tk.Button(window, text="删除选定项", command=lambda: delete_item())
# 将列表框和按钮放置在窗口中
listbox.pack()
button.pack()
# 定义按钮点击事件
def delete_item():
selected = listbox.curselection()
if selected:
listbox.delete(selected)
# 运行窗口
window.mainloop()
4.编写一个程序,爬取百度贴吧中某个贴子的所有图片。
import requests
from bs4 import BeautifulSoup
import os
# 定义爬取图片的函数
def crawl_images(url):
# 发送请求获取网页内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 创建保存图片的文件夹
folder = 'images'
if not os.path.exists(folder):
os.makedirs(folder)
# 爬取图片并保存
images = soup.find_all('img')
for image in images:
image_url = image['src']
if image_url.startswith('http'):
response = requests.get(image_url)
with open(os.path.join(folder, os.path.basename(image_url)), 'wb') as f:
f.write(response.content)
print('保存图片:', image_url)
# 调用爬取图片函数
crawl_images('https://tieba.baidu.com/p/1234567890')
5.编写一个程序,爬取新浪新闻的热门新闻标题和链接。
import requests
from bs4 import BeautifulSoup
# 发送请求获取网页内容
response = requests.get('https://news.sina.com.cn/')
soup = BeautifulSoup(response.text, 'html.parser')
# 爬取热门新闻标题和链接
news_list = soup.find_all('a', class_='news-item')
for news in news_list:
title = news.text.strip()
link = news['href']
print('标题:', title)
print('链接:', link)
print('---')
注释已在代码中添加。
原文地址: https://www.cveoy.top/t/topic/hFPy 著作权归作者所有。请勿转载和采集!