当前位置: 首页>>代码示例>>Python>>正文


Python ScrolledText.config方法代码示例

本文整理汇总了Python中ScrolledText.config方法的典型用法代码示例。如果您正苦于以下问题:Python ScrolledText.config方法的具体用法?Python ScrolledText.config怎么用?Python ScrolledText.config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ScrolledText的用法示例。


在下文中一共展示了ScrolledText.config方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: LogWindow

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
class LogWindow(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title("Network Simulator Log")
        self.text = ScrolledText(self)
        self.text.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        self.text.config(
            background="black",
            foreground="white",
            font=Font(
                family="Courier", weight="bold"),
            # state=DISABLED,
            wrap=NONE, )

        self.text.tag_config("DEBUG", foreground="green")
        self.text.tag_config("ERROR", foreground="red")
        self.text.tag_config("CRITICAL", foreground="red")
        self.text.tag_config("EXCEPTION", foreground="red")
        self.text.tag_config("WARNING", foreground="yellow")
        self.text.tag_config("INFO", foreground="white")

        self.text.bind("<Key>", lambda e: 'break')
        self.text.bind("<Return>", self._clear)
        self.queue = Queue()
        self._update()

    def _clear(self, event):
        self.text.delete(1.0, END)
        return 'break'

    def _update(self):
        try:
            while True:
                text, level = self.queue.get(block=False)

                at_bottom = self.text.yview()[1] == 1.0
                # self.text.config(state=NORMAL)
                if len(self.text.get(1.0, END).strip()) != 0:
                    text = "\n" + text
                self.text.insert(END, text, str(level))
                # self.text.config(state=DISABLED)
                if at_bottom:
                    self.text.yview_moveto(1.0)
        except Empty:
            pass
        self.after(50, self._update)

    def append(self, entry, level="INFO"):
        self.queue.put((entry, level))
开发者ID:VladJamir,项目名称:cmsc135,代码行数:52,代码来源:logviewer.py

示例2: initialisation

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
	def initialisation(self):
		global input_pipe
		global output_pipe

		if len(sys.argv) > 2 :
			print 'output_pipe : ', output_pipe
		global ChaineALire
		global st
		global fp
		global colorbox
		global sortieTube
		global entreeTube



		texte = """ Welcome in GUI for ARINC 653 emulator 
"""

		#on cree un fenetre principale 'fp' a� partir du 'modele' Tk   
		#fp = Tk()
		self.title('ARINC 653 Partition')	

		#Declaration du texte deroulant dans 'fp'
		st = ScrolledText(self,wrap="word")
		st.grid(column=1,columnspan=2,rowspan=2,sticky='nw')

		#Creation d'un panneau 'menu_bottom' insere dans 'fp'
#		menu_bottom = Frame(self,borderwidth=2)
#		menu_bottom.grid(column=1,columnspan=3,sticky='sw')

		##Creation d'une etiquette inseree dans 'menu_bottom'
		#etiquette = Label(menu_bottom,text = 'Commande : ')
		#etiquette.grid(row=1,column=1,sticky='w')

		##Creation d'un boutton dans 'menu_bottom'
		#b = Button(menu_bottom,text='execute',command=self.affiche_commande)
		#b.grid(row=1,column=3,sticky='e')

		##Creation d'un boite d'edition dans 'nenu_top'
		#entre = Entry(menu_bottom,width=20,relief='sunken')
		#entre.insert(END,'Texte a afficher')
		#entre.grid(row=1,column=2,sticky='ew')
			
		#Creation d'une etiquette inseree
		etiquette = Label(self,text = 'Command : ')
		etiquette.grid(row=2,column=0,sticky='w')			
		
		#Creation d'un boutton
		b = Button(self,text='execute',command=self.affiche_commande)
		b.grid(row=2,column=2,sticky='e')

		#Creation d'un boite d'edition dans 'nenu_top'
		entre = Entry(self,width=20,relief='sunken')
		entre.insert(END,'Text to send')
		entre.grid(row=2,column=1,sticky='ew')
		
		partitionbox = Label(self ,text = 'Active partition : ')
		partitionbox.grid(column=0,row=0,sticky='n')
		
		self.labelVariable = StringVar()
		self.backcolorlabel = StringVar()
		self.frontcolorlabel = StringVar()
		self.backcolorlabel = "LightBlue"
		self.frontcolorlabel = "Black"
		label = Label(self,textvariable=self.labelVariable,
			anchor="w",fg=self.frontcolorlabel,bg=self.backcolorlabel,height=28)
		label.grid(column=0,row=1,sticky='EW')
		


		#on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
		st.insert(END,texte)
		#on applique a� tout le texte la police par defaut
		st.config(font = 'Arial 12')
		st.config(foreground='Black')
		#on configure le fond du 'texte derouant'
		st.config(background='LightBlue')
		#e = Entry(st,width=25)


		self.grid_columnconfigure(1,weight=1)
		self.rowconfigure(1,weight=1)
		
		self.resizable(False,True)
		self.update()
		self.geometry(self.geometry())
		
		try:
			assert input_pipe != ''
		
		except AssertionError:
			showerror('error', "no pipe choosed")
			input_pipe = tkFileDialog.askopenfilename(title='Choose the input pipe to open', defaultextension ='.fifo')

		#openning the INPUT pipe
		try:
			assert input_pipe != ''	

			try :

#.........这里部分代码省略.........
开发者ID:ARISSIM,项目名称:ARISS,代码行数:103,代码来源:gui_for_emulator.py

示例3: skulltagBotWindow

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
class skulltagBotWindow(Frame):
	def __init__(self, args='', parent=None):
		Frame.__init__(self, parent)
		
		self.args = args
		self.flags = [0,0,0,0,0]
		self.history = []
		self.players = {'amount': 0}
		self.historyMarker = 0
		self.playerinfoRE = re.compile("([0-9]+)\. ([^%]+?) - IP \(([0-9\.]+:[0-9]+)\)")
		
		for flag, index in (('+dmflags', 0), ('+dmflags2', 1), ('+dmflags3', 2), ('+compatflags', 3), ('+compatflags2', 4)):
			if flag in self.args:
				try:
					self.flags[index] = int(self.args[self.args.index(flag)+1])
				except:
					pass
		
		self.outputText = ScrolledText()
		self.outputText.config(state=DISABLED)
		self.outputText.pack(expand=1, fill='both', anchor='n')
		self.inputTextText = StringVar()
		self.inputText = Entry(textvariable=self.inputTextText)
		self.inputText.bind('<Return>', self.writeLine)
		self.inputText.bind('<Up>', self.upOneHist)
		self.inputText.bind('<Down>', self.downOneHist)
		self.inputText.pack(fill='x', anchor='s')
		self.outputText.tk.call('tk', 'scaling', 1)
		
		self.outputQueue = Queue.Queue()		# just to be orderly
		self.inputQueue = Queue.Queue()			# same
		self.inQLock = thread.allocate_lock()	# well durrrrrr
		self.outQLock = thread.allocate_lock()
		
		thread.start_new(self.startSkulltag, (None,))
		
		self.pack()
	
	def startSkulltag(self, deadArg):
		self.skulltag = subprocess.Popen(['/usr/games/skulltag/skulltag-server', '+sv_markchatlines 1']+self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
		self.stdinPoll = select.poll()
		self.stdinPoll.register(self.skulltag.stdout, select.POLLIN)
		self.stdoutPoll = select.poll()
		self.stdoutPoll.register(self.skulltag.stdout, select.POLLOUT)
		thread.start_new(self.rwLoop, (None,))
	
	def rwLoop(self, deadArg):
		self.readLine()
		try:										#check for input
			output = self.inputQueue.get(block=0)
		except Queue.Empty:
			pass
		else:
			self.inQLock.acquire()
			self.outputText.config(state=NORMAL)
			self.outputText.insert(END, output)		#put it in the main window
			self.outputText.scan_mark(100000, 1)
			self.outputText.scan_dragto(10, 1)
			try:
				lscbot = stbehaviour.LSCParserBot(output, copy.deepcopy(self.players), *self.flags[:])
				chatText = lscbot.get()
						
				if chatText[0]:
					self.skulltag.stdin.flush()
					self.skulltag.stdin.write("say " + chatText[0] + '\n')
				
				self.flags = chatText[2:]
			except:
				import traceback
				print "%s\n%s" % (sys.exc_info()[0], sys.exc_info()[1])
				print traceback.print_tb(sys.exc_info()[2])
				self.cquit()
			self.outputText.config(state=DISABLED)
			self.inQLock.release()
		
		try:										#now for output
			output = self.outputQueue.get(block=0)
		except Queue.Empty:
			pass
		else:
			self.outQLock.acquire()
			self.skulltag.stdin.write(output)
			self.skulltag.stdin.flush()
			self.outQLock.release()
		self.after(5, self.rwLoop, (None,))
	
	def readLine(self):
		output = ''
		scrollAmount = 0
		if self.skulltag.poll():
			output = '\n\n - Terminated - '
			sys.exit()
		else:
			pollin = self.stdinPoll.poll(1)
			while pollin:
				pollin = pollin[0]
				if pollin[1] == 1:
					self.skulltag.stdout.flush()
					output += self.skulltag.stdout.readline()
					scrollAmount += 1
#.........这里部分代码省略.........
开发者ID:IjonTichy,项目名称:PythonTidbits,代码行数:103,代码来源:sttest.py

示例4: TextEditor

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
class TextEditor(EventBasedAnimationClass):

    @staticmethod
    def make2dList(rows, cols):
        # From 15-112 class notes
        a=[]
        for row in xrange(rows): a += [[0]*cols]
        return a

    @staticmethod
    def readFile(filename, mode="rt"):
        # From 15-112 class notes
        # rt = "read text"
        with open(filename, mode) as fin:
            return fin.read()

    @staticmethod
    def writeFile(filename, contents, mode="wt"):
        # From 15-112 class notes
        # wt = "write text"
        with open(filename, mode) as fout:
            fout.write(contents)


    def highlightError(self, lineNumber):
        # highlights error in the code based on line number
        self.textWidget.tag_remove("error",1.0,END)
        self.textWidget.tag_add("error", "%d.0"%lineNumber,
            "%d.end"%lineNumber)
        self.textWidget.tag_config("error", underline = 1)

    def colorIsBlack(self, color):
        # ranks whether a color is nearing black or white
        color = color[1:]
        count = int(color,16)
        if(count<(16**len(color) -1 )/2):
            return True
        return False

    def styleTokens(self,tokenisedText,colorScheme,
                    startIndex,seenlen,seenLines,flag):
        # apply style to tokens in the text
        for token in tokenisedText:
            styleForThisToken = colorScheme.style_for_token(token[0])
            if(styleForThisToken['color']):
                self.currentColor = "#" + styleForThisToken['color'] 
            else:
                if(self.colorIsBlack(colorScheme.background_color)):
                    self.currentColor = "White"
                else: self.currentColor = "Black"
            if(token[1] == "\n"): seenLines += 1
            if(seenLines > 23 and flag): break
            # the '#' is to denote hex value
            textWidget = self.textWidget
            newSeenLen = seenlen + len(token[1])
            textWidget.tag_add(startIndex+"+%dc"%seenlen,
                startIndex+"+%dc"%(seenlen),
                startIndex+"+%dc"%(newSeenLen))
            self.textWidget.tag_config(startIndex+"+%dc"%seenlen,
                foreground = self.currentColor)
            seenlen = newSeenLen

    def checkErrors(self):
        # checks whether there is an error in the code by parsing it
        # and analysing the traceback
        errors = MyParse().pythonCodeContainsErrorOnParse(self.currentText)
        if(errors[0]):
            try:
                lineNumber=int(errors[1][-5][errors[1][-5].find("line ")+5:])
            except:
                lineNumber=int(errors[1][-7][errors[1][-7].find("line ")+5:])
            self.highlightError(lineNumber)
        else:
            self.textWidget.tag_remove("error",1.0,END)

    def highlightText(self,lineCounter = "1",columnCounter = "0",flag = False):
        # highlight text since syntax mode is on
        text = self.currentText.split("\n")
        text = "\n".join(text[int(lineCounter)-1:])
        startIndex = lineCounter + "." + columnCounter
        seenlen, seenLines = 0,0
        tokenisedText = pygments.lex(text, self.lexer)
        if(self.colorScheme):
            colorScheme = pygments.styles.get_style_by_name(self.colorScheme)
        else:
            colorScheme = pygments.styles.get_style_by_name(
                self.defaultColorScheme)
        if(self.colorIsBlack(colorScheme.background_color)):
            self.insertColor = "White"
        else: self.insertColor = "Black"
        self.textWidget.config(background = colorScheme.background_color,
            highlightbackground = colorScheme.highlight_color,
            highlightcolor = colorScheme.highlight_color,
            insertbackground = self.insertColor)
        self.styleTokens(tokenisedText,colorScheme,startIndex,seenlen,
            seenLines, flag)
        if(self.fileExtension == ".py" and self.errorDetectionMode):
            self.checkErrors()

    def editDistance(self,currentWord, word):
#.........这里部分代码省略.........
开发者ID:manikpanwar,项目名称:CollaborativeCoder,代码行数:103,代码来源:textEditor.py

示例5: ChatClient

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
class ChatClient(Frame):
  
  def __init__(self, root):
    Frame.__init__(self, root)
    self.root = root
    self.initUI()
    self.serverSoc = None
    self.serverStatus = 0
    self.buffsize = 1024
    self.allClients = {}
    self.counter = 0
  
  def initUI(self):
    self.root.title("Simple P2P Chat Client")
    ScreenSizeX = self.root.winfo_screenwidth()
    ScreenSizeY = self.root.winfo_screenheight()
    self.FrameSizeX  = 690
    self.FrameSizeY  = 690
    FramePosX   = (ScreenSizeX - self.FrameSizeX)/2
    FramePosY   = (ScreenSizeY - self.FrameSizeY)/2
    self.root.geometry("%sx%s+%s+%s" % (self.FrameSizeX,self.FrameSizeY,FramePosX,FramePosY))
    self.root.resizable(width=False, height=False)
    
    padX = 10
    padY = 10
    parentFrame = Frame(self.root)
    parentFrame.grid(padx=padX, pady=padY, stick=E+W+N+S)
    
    ipGroup = Frame(parentFrame)
    serverLabel = Label(ipGroup, text="Set: ")
    self.nameVar = StringVar()
    self.nameVar.set("Username")
    nameField = Entry(ipGroup, width=20, textvariable=self.nameVar)
    self.serverIPVar = StringVar()
    self.serverIPVar.set("127.0.0.1")
    serverIPField = Entry(ipGroup, width=15, textvariable=self.serverIPVar)
    self.serverPortVar = StringVar()
    self.serverPortVar.set("8090")
    serverPortField = Entry(ipGroup, width=5, textvariable=self.serverPortVar)
    serverSetButton = Button(ipGroup, text="Set", width=10, command=self.handleSetServer)
    addClientLabel = Label(ipGroup, text="Add friend: ")
    self.clientIPVar = StringVar()
    self.clientIPVar.set("127.0.0.1")
    clientIPField = Entry(ipGroup, width=15, textvariable=self.clientIPVar)
    self.clientPortVar = StringVar()
    self.clientPortVar.set("8090")
    clientPortField = Entry(ipGroup, width=5, textvariable=self.clientPortVar)
    clientSetButton = Button(ipGroup, text="Add", width=10, command=self.handleAddClient)
    serverLabel.grid(row=0, column=0)
    nameField.grid(row=0, column=1)
    serverIPField.grid(row=0, column=2)
    serverPortField.grid(row=0, column=3)
    serverSetButton.grid(row=0, column=4, padx=5)
    addClientLabel.grid(row=0, column=5)
    clientIPField.grid(row=0, column=6)
    clientPortField.grid(row=0, column=7)
    clientSetButton.grid(row=0, column=8, padx=5)
    
    readChatGroup = Frame(parentFrame)
    self.profil = ScrolledText(readChatGroup, bg="white", width=50, height=10, state=DISABLED)
    self.receivedChats = ScrolledText(readChatGroup, bg="white", width=55, height=20, state=DISABLED)
    self.friends = Listbox(readChatGroup, bg="white", width=30, height=20)
    self.profil.pack(fill=X, pady=5)
    self.receivedChats.pack(padx=0, pady=10, side=LEFT)
    self.friends.pack(padx=5, pady=10, side=LEFT)

    writeChatGroup = Frame(parentFrame)
    self.chatVar = StringVar()
    self.chatField = Entry(writeChatGroup, width=90, textvariable=self.chatVar)
    sendChatButton = Button(writeChatGroup, text="Kirim", width=15, command=self.handleSendChat)
    self.chatField.grid(row=0, column=0, sticky=W)
    sendChatButton.grid(row=0, column=1, padx=5)
    self.statusLabel = Label(parentFrame)
    bottomLabel = Label(parentFrame, text="Modified By CREVION - PTIIK")
    ipGroup.grid(row=0, column=0)
    readChatGroup.grid(row=1, column=0)
    writeChatGroup.grid(row=2, column=0, pady=10)
    self.statusLabel.grid(row=3, column=0)
    bottomLabel.grid(row=4, column=0, pady=10)
    self.profil.config(state=NORMAL)
    
    self.profil.insert("end","Profil :\n\n")
    self.profil.config(state=DISABLED)
  def handleSetServer(self):
    if self.serverSoc != None:
        self.serverSoc.close()
        self.serverSoc = None
        self.serverStatus = 0
    serveraddr = (self.serverIPVar.get().replace(' ',''), int(self.serverPortVar.get().replace(' ','')))
    try:
        self.serverSoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serverSoc.bind(serveraddr)
        self.serverSoc.listen(5)
        self.setStatus("Server listening on %s:%s" % serveraddr)
        thread.start_new_thread(self.listenClients,())
        self.serverStatus = 1
        self.name = self.nameVar.get().replace(' ','')
        if self.name == '':
            self.name = "%s:%s" % serveraddr
    except:
#.........这里部分代码省略.........
开发者ID:singgihsaputra,项目名称:Chat-using-Phyton,代码行数:103,代码来源:chatApp.py

示例6: initialisation

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
	def initialisation(self):
		global input_pipe
		global output_pipe
		if len(sys.argv) > 2 :
			print 'output_pipe : ', output_pipe
		global ChaineALire
		global st
		global fp
		global sortieTube
		global entreeTube
					
		def click_python(event):
			st.insert(END,'\nVous avez cliquez sur Python')

		def affiche_message():
			global output_pipe
			message = entre.get()
			
			#openning the OUTPUT pipe
			if len(sys.argv) > 2 : #if an output pipe was given as the second argument
				try:
					assert output_pipe != ''
					#opening the pipe
					try :
						entreeTube = os.open(output_pipe,os.O_WRONLY)
						if entreeTube == -1 :
							raise ValueError
						os.write(entreeTube,message)
						#st.insert(END,'\n'+message,'rouge')						
					except ValueError :
						showerror('Error', "Could not open Output pipe")
				except AssertionError:
					showerror("Error", "You must choose an output pipe first")
					output_pipe = tkFileDialog.askopenfilename(title='Choose the output pipe to open', defaultextension ='.fifo')

		texte = """ Welcome in GUI for ARINC 653 Partition """

		#on cree un fenetre principale 'fp' a� partir du 'modele' Tk   
		#fp = Tk()
		#self.title('ARINC 653 function')
		self.title('ARINC 653 function : ' + sys.argv[3])
	
		#Creation d'un panneau 'menu_top' insere dans 'fp'
		menu_top = Frame(self,borderwidth=2)
		menu_top.pack(side='bottom',fill='x')

		#Creation d'une etiquette inseree dans 'menu_top'
		etiquette = Label(menu_top,text = 'Commande : ')
		etiquette.pack(side = 'left')

		#Creation d'un boutton dans 'menu_top'
		b = Button(menu_top,text='execute',command=affiche_message)
		b.pack(side='right')

		#Creation d'un boite d'edition dans 'nenu_top'
		entre = Entry(menu_top,width=20,relief='sunken')
		entre.insert(END,'Texte a afficher')
		entre.pack(side='left',fill='x',expand='true')
	

	
		#Declaration du texte deroulant dans 'fp'
		st = ScrolledText(self)
		st.pack(expand=1,fill='both',side='top')

		#on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
		st.insert(END,texte)
		#on applique a� tout le texte la police par defaut
		st.config(font = 'Arial 12 bold')
		st.config(foreground='Black')
		#on configure le fond du 'texte derouant'
		
		if ((sys.argv[3] == "Master") or (sys.argv[3] == "Partition1")or (sys.argv[3] == "Primary")):
			st.config(background='LightYellow')
		elif ((sys.argv[3] =="Slave") or (sys.argv[3] == "Partition2")or (sys.argv[3] == "Backup")):
			st.config(background='LightGreen')
		#e = Entry(st,width=25)
		elif ((sys.argv[3] =="Leica") or (sys.argv[3] == "Partition3")or (sys.argv[3] == "Capteur")):
		        st.config(background='misty rose')
		else: 
		        st.config(background='PeachPuff')
		try:
			assert input_pipe != ''
		
		except AssertionError:
			showerror('Info', "choisissez un chemin de tube")
			input_pipe = tkFileDialog.askopenfilename(title='Choose the input pipe to open', defaultextension ='.fifo')

		#openning the INPUT pipe
		try:
			assert input_pipe != ''	

			try :

	#			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
				sortieTube = os.open(input_pipe,os.O_RDONLY)
				if sortieTube == -1 :
					raise ValueError
			except ValueError :		
				showerror('Error', "fail to open the Input pipe's output")
#.........这里部分代码省略.........
开发者ID:ARISSIM,项目名称:ARISS,代码行数:103,代码来源:gui.py

示例7: __init__

# 需要导入模块: import ScrolledText [as 别名]
# 或者: from ScrolledText import config [as 别名]
class Textee:
    def __init__(self, master):
        self.master = master
        self.theme = 'dark' # the startup will always be opposite
        self.options = TexteeOptions()
        self.status_bar = TexteeStatusBar(master)
        self.create_menu(master)
        self.create_ui(master)
        self.set_bindings(master)
        self.file = None
        self.find_text = ''
        self.font_dialog = None
        self.find_and_replace_dialog = None
        self.windows = []
        
    def create_menu(self, master):
        self.menu = Menu(master)
        master.config(menu=self.menu)
        
        filemenu = Menu(self.menu)
        self.menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self.new_file)
        filemenu.add_command(label="Open...", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        filemenu.add_command(label="Save As", command=lambda: self.save_file(save_as=True))
        filemenu.add_separator()
        filemenu.add_command(label="New window", command=self.new_window)
        filemenu.add_separator()
        filemenu.add_command(label="Print", command=self.printer)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit)

        editmenu = Menu(self.menu)
        self.menu.add_cascade(label='Edit', menu=editmenu)
        editmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        editmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        editmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        editmenu.add_separator()
        editmenu.add_command(label='Goto', command=self.goto_line) # need to develop custom find with regex
        editmenu.add_command(label='Find', command=self.find) # need to develop custom find with regex
        editmenu.add_command(label='Find & Replace', command=self.find_and_replace) # need to test the replace logic in separate playground
        editmenu.add_separator()
        editmenu.add_command(label='Check spelling', command=self.spell_check) # need to see how to use system's grammer check.. if not possible remove it.

        formatmenu = Menu(self.menu)
        self.menu.add_cascade(label='Format', menu=formatmenu)
        formatmenu.add_command(label='Font', command=self.select_font) # pop-up to select system fonts
        formatmenu.add_checkbutton(label='Wrap', onvalue=True, offvalue=False, variable=self.options.wrap, command=self.toggle_wrap)
        
        viewmenu = Menu(self.menu)
        self.menu.add_cascade(label='View', menu=viewmenu)
        viewmenu.add_checkbutton(label='Status bar', onvalue=True, offvalue=False, variable=self.options.status_bar, command=lambda: self.status_bar.display(self.options.status_bar.get()))
        viewmenu.add_command(label='Toggle theme', command=self.toggle_theme)
        
        helpmenu = Menu(self.menu)
        self.menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About", command=lambda : self.about())

    def create_ui(self, master):
        self.editor = ScrolledText(master, width=100, height=50, highlightthickness=0)
        self.editor.config(undo=True)
        self.editor.pack(expand=YES, fill='both', padx=0, pady=0)
        self.toggle_theme()
        #print_configs(self.editor)
        
        # Create pop-menu for the entire editor.. do some cool stuff with it
        self.editor.popmenu = Menu(self.master, tearoff=0)
        # TODO : later need to do smart copy/paste i.e. selected text copy of entire line copy
        self.editor.popmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        self.editor.popmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        # TODO : disable undo when not available, not sure if its possible. Need to check research later
        self.editor.popmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        self.editor.popmenu.add_separator()
        # TODO : 'share' this will be the best feature in the editor, share the file with the future textee sharing api
        self.editor.popmenu.add_command(label='Share', command=do_nothing)

        # add status bar by default, it can be hidden from menu
        self.status_bar.update_status('Hi there')
        
    def set_bindings(self, master):
        master.bind_class('Text', '<Control-a>', select_all)
        master.bind_class('Text', '<Control-s>', lambda event: self.save_file())
        master.bind_class('Text', '<Control-o>', lambda event: self.open_file())
        master.bind_class('Text', '<Control-n>', lambda event: self.new_file())
        master.bind_class('Text', '<Control-g>', lambda event: self.goto_line())
        master.bind_class('Text', '<Control-f>', lambda event: self.find())
        master.bind_class('Text', '<Control-p>', lambda event: self.printer())
        master.bind_class('Text', '<Control-;>', lambda event: self.find_and_replace()) # this function is only for temporoy use - for dev purpose only

        # editor section bindings only
        self.editor.bind('<Button-2>', self.show_right_click_menu) # for right-click
        self.editor.bind('<Button-3>', self.show_right_click_menu) # for middle-click (scroll press)

        #display the current cursor position
        self.display_current_position()


    def new_file(self):
        self.file = None
        self.editor.delete('1.0', END+'-1c') # clear all the contents
#.........这里部分代码省略.........
开发者ID:rajeshvaya,项目名称:playground-textee,代码行数:103,代码来源:Textee.py


注:本文中的ScrolledText.config方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。