GUI. User input. Multi-line text box - python

A simple GUI where a user can input multiline text is needed. Here is my code how can I get the value from the form? Do I have to manually create buttons too?
I like the simplicity of gooey module but it seems its unable to make multiline textbox? What would be the best way to get the subject done?
import tkinter as tk
root=tk.Tk()
text=tk.Text(root)
text.pack()
root.mainloop()

like this (Python2.7):
from Tkinter import *
root=Tk()
text=Text(root)
text.pack()
gui = {}
gui["text"] = text
def keyUp(e):
print e.keycode
oldText = gui["text"].get(1.0,END)
oldText = oldText[:-1] if (oldText[-1] == u"\n") else oldText
if e.keycode in (36,104) :
gui["text"].delete(1.0,END)
if ord(oldText[-1]) != 10 :
newText = oldText + "\n"
gui["text"].insert("1.0",newText)
else :
gui["text"].insert("1.0",oldText)
gui["text"].update()
gui["text"].insert(1.0,u"Re hello\nWorld\n")
gui["text"].bind("<KeyRelease>", lambda event: keyUp(event))
root.mainloop()
Suppress all new line characters on the keyboard.(i got 36(alpha),104(numlock)). Some operating systems may be able to add lines to the writing box(my big Enter Key). Ignore if the last character is a new line character oldText = oldText[:-1] if (oldText[-1] == u"\n") else oldText.Without forgetting, you cannot add blank lines!

Related

How to highlight last added text in text widget tkinter

I want to highlight a last added text in my text widget.
I have seen an example regarding that How to highlight text in a tkinter Text widget.The problem is that I add a text with "\n". That's why program consider current line as a new line so it highlights the empty line.
Do you have any idea how I can alter the program? Here is my code
import time
import tkinter as tk
from threading import Thread
class MyApp:
def __init__(self, master):
self.master = master
self.text = tk.Text(self.master)
self.text.pack(side="top", fill="both", expand=True)
self.text.tag_configure("current_line", background="#e9e9e9")
self.start_adding_text()
self._highlight_current_line()
def start_adding_text(self):
thrd1 = Thread(target=self.add_tex)
thrd1.start()
def add_tex(self):
text = "This is demo text\n"
for _ in range(20):
self.text.insert(tk.END, text)
time.sleep(0.1)
return
def _highlight_current_line(self, interval=100):
'''Updates the 'current line' highlighting every "interval" milliseconds'''
self.text.tag_remove("current_line", 1.0, "end")
self.text.tag_add("current_line", "insert linestart", "insert lineend+1c")
self.master.after(interval, self._highlight_current_line)
if __name__ == '__main__':
root = tk.Tk()
app = MyApp(master=root)
root.mainloop()
Your function _highlight_current_line is doing what it is supposed to do: it highlights the line of the insert-cursor. But what you want is to highlight the last inserted text which is something different. You can simply create a new tag.
Let's name it 'last_insert':
self.text.tag_configure("last_insert", background="#e9e9e9")
And when you add text, you can specifiy the tag(s) attached to the inserted text:
self.text.insert(tk.END, text, ('last_insert',))
Of course, if you want only the last inserted text to be highlighted, you add this:
self.text.tag_remove("last_insert", 1.0, "end")
Remark: The tkinter function tag_add takes as arguments tag, start, end, where start and end are text indices in the form of a string 'a.b' where a is the line index (starting with 1 at the top) and b is the character inside this line (starting with 0). You can modify the index with expressions (see here: http://effbot.org/tkinterbook/text.htm. Further, "insert" is a mark (read up on aforementioned link) - and "insert linestart" is replaced by tkinter by the index "line.0" where line is the line the insert cursor is currently in.
You could check if you are at the last line and remove your newline:
def add_tex(self):
loop_times=20
text = "This is demo text\n"
for id,_ in enumerate(list(range(loop_times))):
if id==loop_times-1:
text = "This is demo text"
self.text.insert(tk.END, text)
time.sleep(0.1)
return

How to use the module "re " to display the content of text file on text box

I am doing the Final Year Project about the GUI of Aircrack-ng. In my GUI design, the result of cracking password will be write into the text file. And that i write the code to read the text file and display the content what i need . Now i can display some information(Target AP,ESSID ,KEY) on the testbox. I also need to display the ASCII password. I have to refer the document about re (https://docs.python.org/2/library/re.html) and try it but not successful. I hope someone can teach me how to do.Thank you.
This is the text file about the result of cracking password
https://drive.google.com/open?id=192IQr5Y2VUjIZBdUrAlD5uyQQ8YSOUDw
This is the function and GUI Design about display the detail for wep password
# Use pandas to filter the results and display to textbox
def wepresult():
result = re.search(r"\[([^[]+[^(])\]", wepcrackresult_text.get("1.0", 'end-1c'))
if result:
wepcrackresult_text.delete(0.0, END)
wepcrackresult_text.insert(INSERT, "Target ESSID: " + self.controller.shared_data[
"ESSID"].get() + "\nTarget MAC address: " + self.controller.shared_data[
"BSSID"].get() + "\nKEY:" + result.group(1))
GUI Design
wepcrackresult_button = tk.Button(self, text='4.Check', font='Verdana 14',command = wepresult)
wepcrackresult_button.place(x=2, y=630)
Below is the simplest code I can think of:
import tkinter as tk
def display_file(file_path):
txt.delete('1.0', 'end')
with open(file_path) as f:
file_content_as_string = f.read()
# regex filterings can be made in filte_content_as_string
txt.insert('1.0', file_content_as_string)
if __name__ == '__main__':
root = tk.Tk()
txt = tk.Text(root)
# replace __file__ with path
display_file(__file__)
txt.pack()
root.mainloop()

How can I remove newline character (\n) at the end of Text widget?

I am working on a Tkinter GUI.
I am wondering how can I remove newline character (\n) at the end of Text widget? It's making my App looking ugly I don't want this.
Example code is:
from tkinter import *
from tkinter import ttk
window = Tk()
window.title('Advanced Calculator v0.9')
window.geometry('500x400')
window.resizable(False, False)
window.configure(background='black')
hist_t = Text(window, background='black', height='7', foreground='red', font='Verdana', highlightcolor='grey', highlightthickness=1, relief='solid')
Label(window, text='History:', background='black', foreground='red').pack(pady=3, anchor='w')
hist_t.pack(fill='x', padx=3)
hist_t.insert('end', '4 + 4 = 8\n2 + 2 = 4\n5 + 3 = 8\n10 + 13 = 23\n30 + 10 = 40\n12 + 8 = 20')
window.mainloop()
Thanks.
Assert:
hist_t = tk.Text(...)
You can always call hist_t.delete('end-1c', 'end') whenever you want to remove the last char, which is newline in this case. You can also remove the last char only if it is newline:
while hist_t.get('end-1c', 'end') == '\n':
hist_t.delete('end-1c', 'end')
Your problem doesn't appear to be any extra newlines, it's simply that you configured it to show 7 lines but you're only inserting 6. If you set the height to 6 you won't see this blank line.
Textbox always inserts a blank line at the end. The problem was compounded when editing textbox and yet another blank line was inserted. However during edit you could remove blank lines so you can't use "end-1c" all the time.
The trick was to remove 1 or more extra blank lines after editing:
# Rebuild lyrics from textbox
self.work_lyrics_score = \
self.lyrics_score_box.get('1.0', tk.END)
while self.work_lyrics_score.endswith('\n\n'):
# Drop last blank line which textbox automatically inserts.
# User may have manually deleted during edit so don't always assume
self.work_lyrics_score = self.work_lyrics_score[:-1]
Note however this is with Linux. For Windows you might need something like:
while self.work_lyrics_score.endswith('\n\r\n\r'):
# Drop last blank line which textbox automatically inserts.
# User may have manually deleted during edit so don't always assume
self.work_lyrics_score = self.work_lyrics_score[:-2]
Or whatever the the control code is for DOS/Windows LF/CR (Line Feed / Carriage Return) typewriter days style is.

Python Tkinter Gui Not Working

I have had an issue with this piece of code from awhile back, it's part of a GCSE mock and I have currently finished the working code (with text only) but I would like to expand it so that it has a nice GUI. I'm getting some issues with updating my sentence variables within the code. Anyone with any suggestions for me please do explain how I can fix it.
#GCSE TASK WITH GUI
import tkinter
from tkinter import *
from tkinter import ttk
var_sentence = ("default")
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Sentence")
window.geometry("400x300")
window.wm_iconbitmap("applicationlogo.ico")
file = open("sentencedata.txt","w")
file = open("sentencedata.txt","r")
def update_sentence():
var_sentence = sentence.get()
def submit():
file.write(sentence)
print ("")
def findword():
messagebox.showinfo("Found!")
print ("Found")
sentencetext = tkinter.Label(window, fg="purple" ,text="Enter Sentence: ")
sentence = tkinter.Entry(window)
sentencebutton = tkinter.Button(text="Submit", fg="red" , command=update_sentence)
findword = tkinter.Label(window, fg="purple" ,text="Enter Word To Find: ")
wordtofind = tkinter.Entry(window)
findwordbutton = tkinter.Button(text="Find!", fg="red" ,command=findword)
usersentence = sentence.get()
usersentence = tkinter.Label(window,text=sentence)
shape = Canvas (bg="grey", cursor="arrow", width="400", height="8")
shape2 = Canvas (bg="grey", cursor="arrow", width="400", height="8")
#Packing & Ordering Moduales
sentencetext.pack()
sentence.pack()
sentencebutton.pack()
shape.pack()
findword.pack()
wordtofind.pack()
findwordbutton.pack()
usersentence.pack()
shape2.pack()
window.mainloop()
If I understand your question right, you want to display the entered text in the usersentence label.
Changing update_sentence() function to what is shown below will archive the desired effect.
def update_sentence():
var_sentence = sentence.get()
usersentence.config(text=var_sentence)
usersentence never gets updated because you only set it once when the program starts this was the problem.

raw_input stops GUI from appearing

I have written a program in Python that allow me to change the names of many files all at once. I have one issue that is quite odd.
When I use raw_input to get my desired extension, the GUI will not launch. I don't get any errors, but the window will never appear.
I tried using raw_input as a way of getting a file extension from the user to build the file list. This program will works correctly when raw_input is not used.The section of code that I am referring to is in my globList function. For some reason when raw_imput is used the window will not launch.
import os
import Tkinter
import glob
from Tkinter import *
def changeNames(dynamic_entry_list, filelist):
for index in range(len(dynamic_entry_list)):
if(dynamic_entry_list[index].get() != filelist[index]):
os.rename(filelist[index], dynamic_entry_list[index].get())
print "The files have been updated!"
def drawWindow(filelist):
dynamic_entry_list = []
my_row = 0
my_column = 0
for name in filelist:
my_column = 0
label = Tkinter.Label(window, text = name, justify = RIGHT)
label.grid(row = my_row, column = my_column)
my_column = 1
entry = Entry(window, width = 50)
dynamic_entry_list.append(entry)
entry.insert(0, name)
entry.grid(row = my_row, column = my_column)
my_row += 1
return dynamic_entry_list
def globList(filelist):
#ext = raw_input("Enter the file extension:")
ext = ""
desired = '*' + ext
for name in glob.glob(desired):
filelist.append(name)
filelist = []
globList(filelist)
window = Tkinter.Tk()
user_input = drawWindow(filelist)
button = Button(window, text = "Change File Names", command = (lambda e=user_input: changeNames(e, filelist)))
button.grid(row = len(filelist) + 1 , column = 1)
window.mainloop()
Is this a problem with raw_input?
What would be a good solution to the problem?
This is how tkinter is defined to work. It is single threaded, so while it's waiting for user input it's truly waiting. mainloop must be running so that the GUI can respond to events, including internal events such as requests to draw the window on the screen.
Generally speaking, you shouldn't be mixing a GUI with reading input from stdin. If you're creating a GUI, get the input from the user via an entry widget. Or, get the user input before creating the GUI.
A decent tutorial on popup dialogs can be found on the effbot site: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm

Categories

Resources