gpt4 book ai didi

python - 在 Python(或其他)GUI 中显示漂亮的 Python 代码

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:02 24 4
gpt4 key购买 nike

我正在启动一个简单的小 GUI,用于给我学生的 Python 源代码评分。有没有一种简单的方法可以在 GUI 中自动格式化 python 代码的显示?例如,从某个编辑器中提取颜色格式?

我已经开始使用 Python tkk(只是为了一些额外的 python 练习,我教它但不经常使用它)但是如果在这方面更容易,我不反对切换语言。

输出将是一个包含所有成绩等的网页,但会使用 Google Prettify 显示 python 代码(除非有人有更好的建议),所以我不需要保留配色方案,只需要显示它即可评分更容易。

非常感谢!

最佳答案

只记得 wxPython 与 SciTe 捆绑在一起:

#!/usr/bin/env python

import wx
from wx import stc
import keyword

class PyDialog(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, 'Python Code')
sizer = wx.BoxSizer(wx.VERTICAL)

self.stc = stc.StyledTextCtrl(self, -1)
self.stc.SetSizeHints(400, 400)
self.stc.SetLexer(stc.STC_LEX_PYTHON)
self.stc.SetKeyWords(0, " ".join(keyword.kwlist))
self.stc.SetMarginType(1, stc.STC_MARGIN_NUMBER)
# Python styles
self.stc.StyleSetSpec(wx.stc.STC_P_DEFAULT, 'fore:#000000')
# Comments
self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTLINE, 'fore:#008000,back:#F0FFF0')
self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, 'fore:#008000,back:#F0FFF0')
# Numbers
self.stc.StyleSetSpec(wx.stc.STC_P_NUMBER, 'fore:#008080')
# Strings and characters
self.stc.StyleSetSpec(wx.stc.STC_P_STRING, 'fore:#800080')
self.stc.StyleSetSpec(wx.stc.STC_P_CHARACTER, 'fore:#800080')
# Keywords
self.stc.StyleSetSpec(wx.stc.STC_P_WORD, 'fore:#000080,bold')
# Triple quotes
self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLE, 'fore:#800080,back:#FFFFEA')
self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, 'fore:#800080,back:#FFFFEA')
# Class names
self.stc.StyleSetSpec(wx.stc.STC_P_CLASSNAME, 'fore:#0000FF,bold')
# Function names
self.stc.StyleSetSpec(wx.stc.STC_P_DEFNAME, 'fore:#008080,bold')
# Operators
self.stc.StyleSetSpec(wx.stc.STC_P_OPERATOR, 'fore:#800000,bold')
# Identifiers. I leave this as not bold because everything seems
# to be an identifier if it doesn't match the above criterae
self.stc.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, 'fore:#000000')

# Caret color
self.stc.SetCaretForeground("BLUE")
# Selection background
self.stc.SetSelBackground(1, '#66CCFF')

sizer.Add(self.stc, 0, wx.EXPAND)

button = wx.Button(self, -1, 'Open...')
self.Bind(wx.EVT_BUTTON, self.OnOpen, button)
sizer.Add(button)

self.SetSizer(sizer)
sizer.Fit(self)

def OnOpen(self, evt):
dlg = wx.FileDialog(
self,
message = 'Choose File',
wildcard = 'Python source (*.py)|*.py',
style = wx.OPEN)

if dlg.ShowModal() != wx.ID_OK:
return

with open(dlg.GetPath()) as fo:
self.stc.SetText(fo.read())

dlg.Destroy()


if __name__ == '__main__':
app = wx.PySimpleApp()
dlg = PyDialog()
with open(__file__) as fo:
dlg.stc.SetText(fo.read())
dlg.ShowModal()

关于python - 在 Python(或其他)GUI 中显示漂亮的 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com