What is a way to convert text to a string in Python 3.3.0 - python-3.3

Hi so i'm having a hard time getting Text from my program on Python to convert to a string so i can write it to a file without it just writing numbers in the file. i put this code :
from tkinter import *
a = Tk()
a.title("i need help")
a.geometry("600x600")
entryText = StringVar(None)
codeEdit = Text(a)
codeEdit.insert(END, "")
codeEdit.pack(side='top')
text = str(codeEdit)
def setLoc():
saveFile = open("DATA\Test.txt", "w")
saveFile.write(text)
saveFile.close()
return
writeButton = Button(text="Write",command=setLoc)
writeButton.pack(side='bottom')
so thats the code to write the obj locFile to the file Test.txt but when i type something in the Text box on the program and hit the writButton it will write to the file just not what i typed in it puts .50132192 so i wanted to know how i could convert it to a String?

You need to use the Text widget's get method to get all of the text from '1.0' (line 1, character 0) to END.
Here's a modified version of your code that does this in a write_text function. I also added scroll bars and switched to using grid instead of pack.
from tkinter import *
from tkinter import ttk
def write_text():
text = edit.get('1.0', END)
with open("DATA/Test.txt", "w") as f:
f.write(text)
root = Tk()
root.title("This May Help")
root.geometry("600x600")
edit = Text(root, width=80, height=25, wrap=NONE)
edit.insert('1.0', '[enter text]')
edit.grid(column=0, row=0, sticky=(N,W,E,S))
yscroll = ttk.Scrollbar(root, orient=VERTICAL, command=edit.yview)
yscroll.grid(column=1, row=0, sticky=(N,S))
edit['yscrollcommand'] = yscroll.set
xscroll = ttk.Scrollbar(root, orient=HORIZONTAL, command=edit.xview)
xscroll.grid(column=0, row=1, sticky=(W,E))
edit['xscrollcommand'] = xscroll.set
write_button = Button(text="Write", command=write_text)
write_button.grid(column=0, row=2)

Related

How to remove the option to select what's inside a text widget, (not by using state = disabled)

I have tried using exportselection = False
this is the code I use to get the input from the user, if the user is highlighting the text widget (while inputting their answer), they are able to edit where the input get's printed
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
numb_of_times = 5
window.geometry('1920x1080')
window.configure(bg = 'blue')
input_board = tk.Text(window,state = "disabled")
input_board.pack()
input_board.place(x = 100,y = 40)
def send():
input_board.configure(state="normal")
input_board.insert(tk.INSERT, '%s\n' % user_input)
input_board.configure(state="disabled")
for i in range(numb_of_times):
user_input = input()
print(user_input)
send()
window.mainloop()
I have tried using exportselection = False
When the selection changes in the text widget, it emits a <<Selection>> event. You can bind to that event and remove the selection. This should prevent any text from being selected.
The selection is represented by the tag "sel", which you can pass to tag_remove.
The solution might look something like this:
def remove_selection(event):
event.widget.tag_remove("sel", "1.0", "end")
input_board.bind("<<Selection>>", remove_selection)

Trying to put that i made in my Tkinter GUI directly into a file

from tkinter import *
root = Tk()'
root.geometry('500x500')
root.title("Auto Assign Widget")
cw=StringVar()
pp=StringVar()
mt=StringVar()
bdt=StringVar()
def printt(): #Print command
cw1=cw.get()
pp1=pp.get()
mt1=mt.get()
bdt1=bdt.get()
print("M48")
print(f"Cu, {cw1}")
print(f"PP, {pp1}")
print(f"Mat, {mt1}")
print(f"Thk, {bdt1}")
print("%")
def exitt(): #Defining the exit fucntion for the exit button command
exit()
label_0=Label(root, text="Schmoll Auto Assign Widget", relief='solid')
label_0.place(x=200, y=150)
list1=['Qoz', 'Toz', 'Hoz', '1oz']
droplist=OptionMenu(root, cw, *list1)
cw.set("Copper Weight")
droplist.config(width=15)
droplist.place(x=80, y=240)
list2=['1x106', '1x1027', '1x1080', '1x1067']
droplist=OptionMenu(root, pp, *list2)
pp.set("Pre-Preg Style")
droplist.config(width=15)
droplist.place(x=80, y=280)
list3=['370HR', 'MEG6', 'R6202', 'FR408']
droplist=OptionMenu(root, mt, *list3)
mt.set("Material Type")
droplist.config(width=15)
droplist.place(x=80, y=320)
label_1=Label(root, text='Board Thickness')
label_1.place(x=80, y=360)
entry_1= Entry(root, textvar=bdt)
entry_1.place(x=240, y=360)
but_export = Button(root, text = 'Export', command=printt).place(x=150, y=450)
but_quit = Button(root, text='Quit', command=exitt).place(x=280, y=450)
root.mainloop()
And now I would like to try and create another button that sets up a tool path to a directory so i can choose what file i would like to write the information to. Any ideas where i should start looking? I figure that i can do this in Tkinter pretty easy
with open('out.txt', 'w') as f:
print('Filename:', filename, file=f)
^ Thats kinda what i had in my but id like to assign it to a button command where maybe i would open the file and then do my GUI stuff, then have it write itself in. Thanks for all the help!
Add this lines to your code :
1-import filedialog:
from tkinter import filedialog
2-in function printt add :
text="M48\n"+(f"Cu, {cw1}\n")+(f"PP, {pp1}\n")+(f"Mat, {mt1}\n")+(f"Thk, {bdt1}")+"%"
return text
3- Define new function for saving:
def file_save():
text = printt()
f = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
if f is None:
return
with open(f, 'r') as original: data = original.read()
with open(f, 'w') as modified: modified.write(text+"\n" + data)
4- create button for Save:
but_SaveAs = Button(root, text = 'Save as', command=file_save).place(x=50, y=450)

Stop a working function with a button (Python, Tkinter)

I have a little situation with Tkinter. I have a piece of code that constantly receives raw EMG data from Thalmic`s Myo Armband and writes that data (plus the name of a gesture) to a csv file. I designed a little tkinter interface to make it look more user-friendly. What I need is to write a function that will stop the previously started recording function.
Also I have a problem with the label, that shows the number of rows in a csv file, but it is another question.
Here is the code:
from gesture_classificator import MyoRaw
import csv
import tkinter
import tkinter.messagebox
import sys
root = tkinter.Tk()
root.title("Recording data")
m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None)
v = tkinter.StringVar()
entry = tkinter.Entry(root, textvariable=v)
entry.grid(row=0, column=0)
v.set("")
def process_emg(emg, times):
name = v.get()
with open('own_test.csv', 'a+') as file:
writing = csv.writer(file)
writing.writerow(emg+(name,))
def show_row_count():
with open('own_test.csv', 'r') as return_me_the_row_count:
reading = csv.reader(return_me_the_row_count)
data = list(reading)
row_count = len(data)
return row_count
def start_recording():
m.add_emg_handler(process_emg)
m.connect()
def stop_recording():
???
B1 = tkinter.Button(root, text="Start the recording", command=start_recording)
B2 = tkinter.Button(root, text="Stop the recording", command=stop_recording)
rows_number = tkinter.Label(root, text=show_row_count)
rows_number.config(text=show_row_count)
B1.grid(row=1, column=0)
B2.grid(row=1, column=1)
rows_number.grid(row=0, column=1)
root.mainloop()
try:
while True:
m.run(1)
except SystemExit:
pass
finally:
m.disconnect()
According to the MyoRaw code, you would probably like the function MyoRaw.disconnect(), which you would use like this:
def stop_recording():
m.disconnect()
In such cases it would be easier and faster for you to check the documentation and/or the code of the framework you are using.

tkinter need to click in shell to get gui fields to update

I have a tkinter gui with Python 3.4.2 in which there are various buttons, a user entry field and a text field. Everything works except that I appear to have to click in the Python shell (IDLE) and out of the gui to get fields to update in response to button presses. The updates are immediate when I click on the shell. I have copied this tkintergui from http://ubuntuforums.org/showthread.php?t=1156637 which gives the same problem on my Mac. Immediate update if IDLE shell clicked or very slow update in the GUI
#!/usr/bin/python
from tkinter import *
from tkinter.filedialog import *
class SimpleEdApp:
def __init__(self, parent=Tk()):
self.mainWindow = (parent)
self.mainWindow.title("Simple Editor")
self.mainWindow.resizable(0, 0)
self.make_mnu()
self.make_txt()
def make_txt(self):
self.text = Text(self.mainWindow, width = 80, height = 40, background = 'white')
self.scrollY = Scrollbar(self.mainWindow, orient = VERTICAL, command = self.text.yview, troughcolor = 'white')
self.text["yscrollcommand"] = self.scrollY.set
self.scrollY.pack(side = RIGHT, fill = Y)
self.text.pack(expand = TRUE, fill = BOTH)
def make_mnu(self):
self.menubar = Menu(self.mainWindow)
self.filemenu = Menu(self.menubar, tearoff = 0)
self.filemenu.add_command(label = "Open", command = self.file_open)
self.filemenu.add_command(label = "Save as...", command = self.file_save)
self.filemenu.add_separator()
self.filemenu.add_command(label = "Exit", command = self.mainWindow.destroy)
self.menubar.add_cascade(label = "File", menu = self.filemenu)
self.mainWindow.config(menu = self.menubar)
def file_open(self):
filename =askopenfilename(filetypes=[("pythonfiles","*.py"),("tclfiles","*.tcl"),("allfiles","*")])
f = open(filename, 'r')
data = f.read()
f.close()
self.text.delete(1.0, END)
self.text.insert(1.0, data)
def file_save(self):
filename =asksaveasfilename(filetypes=[("pythonfiles","*.py"),("tclfiles","*.tcl"),("allfiles","*")])
f = open(filename, 'w')
data = self.text.get(1.0, END)
f.write(data)
f.close()
app = SimpleEdApp()
app.mainWindow.mainloop()
Grateful for correct implementation
There is nothing wrong with your code. This looks to be a bug in IDLE.
In the comments you asked how to run the program outside of IDLE. To do that, open up a prompt and type the command python myfile.py, where myfile.py is the name of your python file (assuming "python" is in your PATH).
*note: depending on what is installed in your system, you may need to use python3 rather than python.

How can I save output tho the same file that I have got the data from, in Python 3

I am trying to open a file, remove some characters (defined in dic) and then save it to the same the file.
I can print the output and it looks fine, but I cannot save it into the same file that the original text is being loaded from.
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
import sys
import fileinput
dic = {'/':' ', '{3}':''};
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Napisy", "*.txt"),
("All files", "*.*") ))
if fname:
try:
with open (fname, 'r+') as myfile: #here
data = myfile.read() #here
data2 = replace_all(data, dic) #here
print(data2) #here
data.write(data2) #and here should it happen
except:
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
I have tried several commands but either I am receiving python errors or it is simply not working.
This is often implemented by writing to a temp file and then moving it to the original file's name.
Strings do not have a .write method. The following should work (I tried it): replace
data.write(data2) #and here should it happen
with
myfile.seek(0)
myfile.truncate()
myfile.write(data2)
The truncate() call is needed if data2 is shorter than data as otherwise, the tail end of data will be left in the file.

Resources