1、设计并编写一个窗口程序,该窗口只有一个按钮,当用户单击时可在后台输出hello
world.
import tkinter as tk
def on_button_click():print("hello world")
# 创建主窗口
root = tk.Tk()
root.title("Hello World Button")
# 设置窗口大小
root.geometry("200x100")
# 创建一个按钮
button = tk.Button(root, text="点击", command=on_button_click)
# 将按钮添加到主窗口
button.pack(pady=20)
# 启动主事件循环
root.mainloop()
2、设计并编写一个窗口程序,该窗口中的第一,第二行都是一个文本框,用于输人账号和密码,第三行是一个“提交"按钮。要求:密码框输人时不显示明文(设置wxTEPASSWORD属性),当用户单击提交时检测账号和密码是否都是admin,如果正确则在后台输出登录成功,否则输出登录失败。
这个要安装wxpython
pip install wxPython
或者在 wxPython · PyPI中下载对应版本的,放入Scripts中,再
python -m pip install wxPython-4.2.1-cp38-cp38-win_amd64.whl#下载的文件名
import wx
class LoginDialog(wx.Dialog):def __init__(self, parent, title):super(LoginDialog, self).__init__(parent, title=title, size=(300, 150))# 创建账号和密码的文本框self.username_ctrl = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)self.password_ctrl = wx.TextCtrl(self, style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER)# 创建提交按钮self.submit_btn = wx.Button(self, label="提交")self.submit_btn.Bind(wx.EVT_BUTTON, self.on_submit)# 布局sizer = wx.BoxSizer(wx.VERTICAL)sizer.Add(wx.StaticText(self, label="账号:"), 0, wx.ALIGN_CENTER | wx.ALL, 5)sizer.Add(self.username_ctrl, 0, wx.EXPAND | wx.ALL, 5)sizer.Add(wx.StaticText(self, label="密码:"), 0, wx.ALIGN_CENTER | wx.ALL, 5)sizer.Add(self.password_ctrl, 0, wx.EXPAND | wx.ALL, 5)sizer.Add(self.submit_btn, 0, wx.ALIGN_CENTER | wx.ALL, 5)self.SetSizerAndFit(sizer)def on_submit(self, event):username = self.username_ctrl.GetValue()password = self.password_ctrl.GetValue()if username == "admin" and password == "admin":print("登录成功")else:print("登录失败")# 应用程序的主类class MyApp(wx.App):def OnInit(self):dialog = LoginDialog(None, title="登录窗口")dialog.ShowModal()dialog.Destroy()return True# 运行应用程序if __name__ == '__main__':app = MyApp(0)app.MainLoop()
3.使用wx.html2或其他网页控件设计并编写一个基本浏览器。功能包括后退、前进、刷新、网址输人框、网页显示。
import wx
import wx.html2 as webview class BrowserFrame(wx.Frame): def __init__(self, title): super().__init__(None, title=title, size=(800, 600)) # 创建面板和布局 panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) # 创建网址输入框 self.url_ctrl = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER) sizer.Add(self.url_ctrl, 0, wx.EXPAND | wx.ALL, 5) # 创建WebView控件 self.browser = webview.WebView.New(panel) sizer.Add(self.browser, 1, wx.EXPAND | wx.ALL, 5) # 创建工具栏按钮 toolbar = self.CreateToolBar() back_btn = toolbar.AddTool(wx.ID_BACKWARD, 'Back', wx.Bitmap('back.png')) # 你需要提供'back.png'图片 forward_btn = toolbar.AddTool(wx.ID_FORWARD, 'Forward', wx.Bitmap('forward.png')) # 你需要提供'forward.png'图片 refresh_btn = toolbar.AddTool(wx.ID_REFRESH, 'Refresh', wx.Bitmap('refresh.png')) # 你需要提供'refresh.png'图片 toolbar.Realize() # 绑定按钮事件 self.Bind(wx.EVT_TOOL, self.OnBackward, id=wx.ID_BACKWARD) self.Bind(wx.EVT_TOOL, self.OnForward, id=wx.ID_FORWARD) self.Bind(wx.EVT_TOOL, self.OnRefresh, id=wx.ID_REFRESH) self.Bind(wx.EVT_TEXT_ENTER, self.OnURLEnter, self.url_ctrl) # 设置面板布局 panel.SetSizer(sizer) # 加载初始页面(可选) self.LoadPage('http://www.example.com') def LoadPage(self, url): self.browser.LoadURL(url) def OnBackward(self, event): if self.browser.CanGoBack(): self.browser.GoBack() def OnForward(self, event): if self.browser.CanGoForward(): self.browser.GoForward() def OnRefresh(self, event): self.browser.Reload() def OnURLEnter(self, event): url = self.url_ctrl.GetValue() self.LoadPage(url) if __name__ == '__main__': app = wx.App(False) frame = BrowserFrame('Simple Browser') frame.Show() app.MainLoop()
4、使用 StyledTextCtr|控件编写一个Python编辑器,功能包括打开、保存、Python 代码颜色渲染(wxPython Demo 中的 advanced Generic Widgets 里的 RulerCtrl中有)。
import wx
import wx.stc as stc
import osclass PythonEditorFrame(wx.Frame):def __init__(self, parent=None, title='Python Editor'):super(PythonEditorFrame, self).__init__(parent, title=title, size=(800, 600))# 创建StyledTextCtrlself.text_ctrl = stc.StyledTextCtrl(self, style=wx.TE_MULTILINE)# 设置lexerself.text_ctrl.SetLexer(stc.STC_LEX_NULL)# 设置样式self.text_ctrl.StyleSetSpec(stc.STC_STYLE_DEFAULT, "fore:#000000,back:#FFFFFF,face:Courier New,size:10")self.text_ctrl.StyleSetSpec(1, "fore:#FF0000") # 假设1是关键字的样式ID# 'def'和'class'关键字设置红色self.text_ctrl.SetText("def function():\n\tprint('Hello, World!')\n\nclass MyClass:\n\tpass")self.text_ctrl.StartStyling(0)self.text_ctrl.SetStyling(3, 1) # 将'def'设置为红色(样式ID 1)self.text_ctrl.SetStyling(19, 1) # 将'class'设置为红色(样式ID 1)# 创建一个简单的菜单(文件 -> 打开/保存)menubar = wx.MenuBar()fileMenu = wx.Menu()open_item = fileMenu.Append(wx.ID_OPEN, '&Open', 'Open a file')self.Bind(wx.EVT_MENU, self.OnOpen, open_item)save_item = fileMenu.Append(wx.ID_SAVE, '&Save', 'Save the file')self.Bind(wx.EVT_MENU, self.OnSave, save_item)menubar.Append(fileMenu, '&File')self.SetMenuBar(menubar)# 布局sizer = wx.BoxSizer(wx.VERTICAL)sizer.Add(self.text_ctrl, 1, wx.EXPAND | wx.ALL, 5)self.SetSizer(sizer)def OnOpen(self, event):"""打开文件对话框,并读取文件内容到StyledTextCtrl"""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("Unable to open file '%s'" % pathname)def OnSave(self, event):"""保存StyledTextCtrl的内容到文件"""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("Unable to save file '%s'" % pathname)if __name__ == '__main__':app = wx.App(False)frame = PythonEditorFrame()frame.Show()app.MainLoop()
5、设计并编写一个简单的计算器程序,功能包括:0~9的数字按键、运算符“十”“-”“*”“/”、=(等号)与C清空按键,以及一个结果显示屏。
import tkinter as tk# 创建一个简单的表达式求值函数
def evaluate_expression(expression):try:return str(eval(expression))except Exception as e:return "错误: " + str(e)# 创建一个计算器类class Calculator:def __init__(self, master):self.master = mastermaster.title("简单计算器")# 结果显示屏self.display = tk.Entry(master, font=('helvetica', 24), width=20, justify='right')self.display.grid(row=0, column=0, columnspan=4, pady=10)# 数字按键for row in range(1, 4):for col in range(4):num = str((row - 1) * 3 + col + 1)button = tk.Button(master, text=num, command=lambda num=num: self.append_to_display(num))button.grid(row=row, column=col, padx=10, pady=10)# 运算符按键ops = ['+', '-', '*', '/']for col, op in enumerate(ops, start=4):button = tk.Button(master, text=op, command=lambda op=op: self.append_to_display(op))button.grid(row=1, column=col, padx=10, pady=10)# 等号按键equal_button = tk.Button(master, text='=', command=self.calculate)equal_button.grid(row=4, column=3, padx=10, pady=10)# 清空按键clear_button = tk.Button(master, text='C', command=self.clear_display)clear_button.grid(row=4, column=2, padx=10, pady=10)def append_to_display(self, text):self.display.insert(tk.END, text)def clear_display(self):self.display.delete(0, tk.END)def calculate(self):try:expression = self.display.get()result = evaluate_expression(expression)self.display.delete(0, tk.END)self.display.insert(tk.END, result)except Exception as e:self.display.delete(0, tk.END)self.display.insert(tk.END, "错误: " + str(e))# 创建主窗口并运行计算器root = tk.Tk()
calc = Calculator(root)
root.mainloop()