专栏python共10次python实验,可去主页python专栏查看
1.设计并编写一个窗口程序,该窗口只有一个按钮,当用户单击时可在后台输出 hello
world。
import tkinter as tk
def on_button_click():
print("hello world")
# 创建主窗口
root = tk.Tk()
root.title("Hello World")
# 创建一个按钮
button = tk.Button(root, text="Click Me!", command=on_button_click)
button.pack(pady=20) # 添加一些垂直填充以使按钮居中
# 运行主循环
root.mainloop()
运行结果:
2.设计并编写一个窗口程序,该窗口中的第一、第二行都是一个文本框,用于输人账号和密码,第三行是一个“提交”按钮。要求:密码框输入时不显示明文(设置wxTEPASSWORD属性),当用户单击提交时检测账号和密码是否都是admin,如果正确则在后台输出登录成功,否则输出登录失败。
import wx
class LoginDialog(wx.Frame):
def __init__(self, title):
super(LoginDialog, self).__init__(None, title=title, size=(300, 200))
# 创建面板
panel = wx.Panel(self)
# 账号文本输入框
self.account_ctrl = wx.TextCtrl(panel, pos=(50, 20), size=(200, -1))
# 密码文本输入框(设置为密码模式)
self.password_ctrl = wx.TextCtrl(panel, pos=(50, 50), size=(200, -1), style=wx.TE_PASSWORD)
# 提交按钮
self.submit_btn = wx.Button(panel, label='提交', pos=(120, 80), size=(60, 30))
self.submit_btn.Bind(wx.EVT_BUTTON, self.on_submit)
# 设置布局(在这个简单的例子中,我们直接使用绝对定位)
# 显示窗口
self.Show()
def on_submit(self, event):
# 获取账号和密码
account = self.account_ctrl.GetValue()
password = self.password_ctrl.GetValue()
# 验证账号和密码
if account == 'admin' and password == 'admin':
print("登录成功")
else:
print("登录失败")
if __name__ == '__main__':
app = wx.App(False)
frame = LoginDialog('登录窗口')
app.MainLoop()
wxpython的安装
运行结果:
3.使用wx.html2或其他网页控件设计并编写一个基本浏览器。功能包括后退、前进、刷新、网址输入框、网页显示。
import wx
import wx.html2 as webview
class MyBrowser(wx.Frame):
def __init__(self, title):
super(MyBrowser, self).__init__(None, title=title, size=(800, 600))
# 创建面板
panel = wx.Panel(self)
# 创建网址输入框
self.url_input = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER)
self.url_input.Bind(wx.EVT_TEXT_ENTER, self.on_load_url)
# 创建WebView控件
self.browser = webview.WebView.New(panel)
# 创建后退、前进和刷新按钮
backward_btn = wx.Button(panel, label='后退')
forward_btn = wx.Button(panel, label='前进')
reload_btn = wx.Button(panel, label='刷新')
# 绑定按钮事件
backward_btn.Bind(wx.EVT_BUTTON, self.on_backward)
forward_btn.Bind(wx.EVT_BUTTON, self.on_forward)
reload_btn.Bind(wx.EVT_BUTTON, self.on_reload)
# 布局
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.url_input, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.browser, 1, wx.EXPAND | wx.ALL, 5)
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(backward_btn, 0, wx.ALL, 5)
button_sizer.Add(forward_btn, 0, wx.ALL, 5)
button_sizer.Add(reload_btn, 0, wx.ALL, 5)
sizer.Add(button_sizer, 0, wx.EXPAND | wx.ALL, 5)
panel.SetSizer(sizer)
# 加载初始页面
self.LoadURL('https://www.example.com')
def on_load_url(self, event):
url = self.url_input.GetValue()
self.LoadURL(url)
def LoadURL(self, url):
self.browser.LoadURL(url)
def on_backward(self, event):
if self.browser.CanGoBack():
self.browser.GoBack()
def on_forward(self, event):
if self.browser.CanGoForward():
self.browser.GoForward()
def on_reload(self, event):
self.browser.Reload()
if __name__ == '__main__':
app = wx.App(False)
frame = MyBrowser('简易浏览器')
frame.Show()
app.MainLoop()
运行结果:
4.使用 StyledTextCtrl控件编写一个 Python编辑器,功能包括打开、保存、Python 代码颜色渲染(wxPython Demo中的 advanced Generic Widgets 里的 RulerCtrl 中有)。
import wx
import wx.stc as stc
import os
import keyword
class PythonEditor(wx.Frame):
def __init__(self, parent=None, title='Python Editor'):
super(PythonEditor, self).__init__(parent, title=title, size=(800, 600))
# 创建一个面板
panel = wx.Panel(self)
# 创建一个StyledTextCtrl控件
self.text_ctrl = stc.StyledTextCtrl(panel, style=wx.TE_MULTILINE | wx.HSCROLL | wx.VSCROLL)
# 设置代码高亮样式
self.text_ctrl.SetLexer(stc.STC_LEX_PYTHON)
self.text_ctrl.SetKeyWords(0, " ".join(keyword.kwlist))
# 添加打开和保存按钮
open_btn = wx.Button(panel, label='Open')
save_btn = wx.Button(panel, label='Save')
# 绑定事件
open_btn.Bind(wx.EVT_BUTTON, self.on_open)
save_btn.Bind(wx.EVT_BUTTON, self.on_save)
# 布局
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.text_ctrl, 1, wx.EXPAND | wx.ALL, 5)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
btn_sizer.Add(open_btn, 0, wx.ALL, 5)
btn_sizer.Add(save_btn, 0, wx.ALL, 5)
sizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5)
panel.SetSizer(sizer)
def on_open(self, event):
"""打开文件并读取内容到文本编辑器"""
with wx.FileDialog(self, "Open Python file", "", "",
"Python files (*.py)|*.py", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # 用户取消了操作
# 读取文件内容
pathname = fileDialog.GetPath()
try:
with open(pathname, 'r') as file:
self.text_ctrl.SetText(file.read())
except IOError:
wx.LogError("Cannot open file '%s'" % pathname)
def on_save(self, event):
"""保存文本编辑器的内容到文件"""
with wx.FileDialog(self, "Save Python file", "", "",
"Python files (*.py)|*.py", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # 用户取消了操作
pathname = fileDialog.GetPath()
try:
with open(pathname, 'w') as file:
file.write(self.text_ctrl.GetText())
except IOError:
wx.LogError("Cannot save to file '%s'" % pathname)
if __name__ == '__main__':
app = wx.App(False)
frame = PythonEditor()
frame.Show()
app.MainLoop()
运行结果:
import tkinter as tk
# 计算函数
def calculate(event=None):
try:
expression = entry.get()
result = eval(expression)
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")
# 清空函数
def clear():
entry.delete(0, tk.END)
# 创建主窗口
root = tk.Tk()
root.title("Simple Calculator")
# 创建结果显示屏
entry = tk.Entry(root, font=('calibri', 24, 'normal'), justify='right', width=30)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# 按键函数
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, str(current) + str(number))
# 运算符和数字按键
row = 1
for i in range(1, 5):
col = 0
for j in range(4):
if i == 1 and (j == 0 or j == 3): # 跳过第一行的前两个和最后两个位置
continue
if i == 2 and j == 1: # 第二行的第二个位置是'-'
tk.Button(root, text='-', width=7, height=3, command=lambda: button_click('-')).grid(row=row, column=col)
elif i == 3 and j == 1: # 第三行的第二个位置是'*'
tk.Button(root, text='*', width=7, height=3, command=lambda: button_click('*')).grid(row=row, column=col)
else:
tk.Button(root, text=str(i * j - 3), width=7, height=3, command=lambda x=i * j - 3: button_click(x)).grid(
row=row, column=col)
col += 1
row += 1
# 运算符和数字按键的第二部分
tk.Button(root, text='/', width=7, height=3, command=lambda: button_click('/')).grid(row=4, column=0)
tk.Button(root, text='7', width=7, height=3, command=lambda: button_click(7)).grid(row=4, column=1)
tk.Button(root, text='8', width=7, height=3, command=lambda: button_click(8)).grid(row=4, column=2)
tk.Button(root, text='9', width=7, height=3, command=lambda: button_click(9)).grid(row=4, column=3)
# 等号和清空按键
tk.Button(root, text='=', width=15, height=3, command=calculate).grid(row=5, column=1, columnspan=2)
tk.Button(root, text='C', width=7, height=3, command=clear).grid(row=5, column=3)
# 运行主循环
root.mainloop()
运行结果:
二、实验总结:(写收获与存在的问题)
第1题实验心得:
我首先导入了tkinter模块,然后,我定义了一个函数on_button_click,当按钮被点击时,这个函数会被调用并输出"hello world"。
接下来,我创建了一个主窗口,并设置了它的标题。然后,我创建了一个按钮(button),设置了它的文本为"Click Me!",并将前面定义的on_button_click函数作为它的command参数。这意味着当按钮被点击时,on_button_click函数将被调用。
最后,我们使用pack方法将按钮添加到主窗口中,并设置了一些垂直填充以使按钮居中。然后,我们调用root.mainloop()来启动Tkinter的事件循环,这将使窗口保持打开状态并等待用户交互。
第2题心得:遇到的最大的问题就是在pycharm里wxpython包总是下载失败,后来发现是我所使用的python3.10版本与wxpython不兼容,后将python版本下载为wxpython兼容版本所包含的3.7版本才完成下载。