python tkinter interface how to create a new to show txt file - python

I buid a code which takes python user input and insert it into a text file when pressing apply as shown in the picture bellow
and the text file will always be updated when the user inserts a new text, how to create an new button next to apply to show up to date text file to the user
and want prevent to enter the same text
example if the text file has a (go) the program do not enter (go) again
this is my code
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("help.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop()

To prevent a user from inserting the same text just empty the two entries, and you can check if entries are not empty before saving to a file.
You can use a top-level window to show the file content.
Check the following example:
from tkinter import Tk, Toplevel, Button, Entry, StringVar, Text, DISABLED, END, W, E
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
if any(content_list):
print("\n".join(content_list))
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
ivn2.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
root.mainloop()
Edited to answer #IbrahimOzaeri question in comments.
You can use tkFileDialog.askopenfilename to ask user to select a file:
from Tkinter import Tk
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
print (root.filename)

I was trying something same but with one output
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
root.geometry("500x300")
root.title("The Gatway company")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get()]
if any(content_list):
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
applyButton.config( height = 5, width = 10 )
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
showButton.config( height = 5, width = 10 )
root.mainloop()
it's same as your code but for one entry, I'm thinking to edit it in a such way that the user chooses the help.txt file like a file requester.

Related

How can I call my second function after my first function?

I have two functions and two GUI.
I cannot get them to work after each other.
first, I want to open my browse GUI then editing GUI.
help me out, please.
from tkinter import *
from tkinter import filedialog
window = Tk()
def fileme():
root = Tk()
root.withdraw()
file_path = filedialog.askopenfilenames(filetypes=[("Text file","*.txt")])
print(file_path)
window.withdraw()
with open(file_path[0]) as f:
f_contents = f.read()
b=(f_contents)
print(b)
window.title('Edit and save text files by Ali')
frame = Frame(window)
btn = Button(frame, text = 'Browse', command= fileme)
btn.pack(side = RIGHT , padx =55)
frame.pack(padx=100,pady = 30)
root=Tk()
x=filedialog.askopenfilename(filetypes=[("Text file","*.txt")])
T=Text(root,state='normal', height=20, width=70)
T.pack()
T.insert(END, open(x).read())
def save():
b = T.get('1.0', END)
f = open(x, 'wt')
f.write(b)
f.close()
btn= Button(root, text='Save', command=save)
btn.pack(side = RIGHT , padx =55)
window.mainloop()
root.mainloop()
I figured it out
Here is an answer to this type of questions.
hope to be useful for anyone who is learning programming.
from tkinter import *
from tkinter import filedialog
window=Tk()
def x():
x=filedialog.askopenfilename(filetypes=[("Text file","*.txt")])
T = Text(window, state='normal', height=20, width=70)
T.pack()
T.insert(END, open(x).read())
def save():
b = T.get('1.0', END)
f = open(x, 'wt')
f.write(b)
f.close()
btn1 = Button(window, text='Save', command=save)
btn1.pack(side=RIGHT, padx=55)
window.title('Edit and save text files by Ali')
frame = Frame(window)
btn = Button(frame, text = 'Browse', command= x)
btn.pack(side = RIGHT , padx =55)
frame.pack(padx=100,pady = 30)
window.mainloop()
#Epiphnac In your solution both the browser window and the text editor open in the same window. I think my solution is a little bit better than that.
I have put the editor inside a new window using Toplevel.
Like this:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
def editor():
x = filedialog.askopenfilename(filetypes=[("Text file", "*.txt")])
new_window = tk.Toplevel()
t = tk.Text(new_window, state='normal', height=20, width=70)
t.pack()
t.insert(tk.END, open(x).read())
def save():
b = t.get('1.0', tk.END)
f = open(x, 'wt')
f.write(b)
f.close()
btn1 = tk.Button(new_window, text='Save', command=save)
btn1.pack(side=tk.RIGHT, padx=55)
window.title('Edit and save text files by Ali')
frame = tk.Frame(window)
btn = tk.Button(frame, text='Browse', command=editor)
btn.pack(side=tk.RIGHT, padx=55)
frame.pack(padx=100, pady=30)
window.mainloop()

how to create a GUI using python to take user input and insert it into excel sheet

I want to create a python GUI with one user input which will be inserted to an excel sheet whenever the user Enters insert button, and another button called e.g Show words, which will read all the words which are inserted into the excel sheet, any ideas how to do that ?
the excel sheet shoud be like this
and the user interface should be something simple like this
some code that I created for GUI but its for text file not excel
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("help.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop() ```
sorry if its silly question but this will be my first python GUI program
You can create GUI using python tkinter, you can also create input fields using this library and accept the entered value. After this you can simple use python csv library to insert a record into sheet.
You can find more information about tkinter Here
Use this code to read data from test.txt (use your txt file) file, insert data into file also as you asked it will also check if same data exist. You can view the data by clicking on view data button.
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def printSomething():
with open('help.txt') as f:
r = f.read()
label = Label(root, text=r)
label.grid()
def checkdata():
with open('help.txt') as f:
r = f.read()
return r.split("\n")
def writetofile():
exist_data = checkdata()
content_list = [ivn.get(), ivn2.get()]
with open("help.txt", "a") as f:
for item in content_list:
if item in exist_data:
msg = "Already exist "+item
label = Label(root, text=msg)
label.grid()
elif not item in exist_data:
f.write("%s\n" % item)
applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)
veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)
root.mainloop()
Note: There are multiple ways to achieve this, one of them is this one.

Write data to file from a list, by tkinter entry

I can't figure out what I'm doing wrong here!
I trying to write/append data from tkinter entry to a txt file. The entries, goes to a list, that I will append to the text file. But it doesn't take my new entry, only my already defined text.
Here is my code:
from tkinter import *
root = Tk()
# Input
# -----------------------------------------------------
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
ivnget = ivn.get()
inputVarName.grid(row=0, column=0)
# Input
# -----------------------------------------------------
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
ivnget2 = ivn2.get()
inputVarName2.grid(row=1, column=0)
# Collecting data (entry)
# --------------------------------------------------------------------------------------
content_list = [ivnget, ivnget2]
# --------------------------------------------------------------------------------------
print("\n".join(content_list))
def writetofile():
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
# Button that applies entries to file
# --------------------------------------------------------------------------------------
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
# --------------------------------------------------------------------------------------
root.mainloop()
You have placed the get commands outside the function writetofile.
Try:
from tkinter import *
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("dataoutput2.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop()

Python: What is the syntax for adding a command to a tkinter Listbox item?

below is my code for creating a tool that takes a file path, stores the value, and then opens the specific file path selected by the user.
Currently, I'm looking to take the user entry mypathEntry that is stored in the mypathList listbox after clicking the Save button and add a command to it. The command will open that selected file path. My current code returns an error message regarding mypathList.add_command(command=Open) stating that Listbox instance has no attribute 'add_command'.
What is the syntax for adding a command to a listbox item?
from Tkinter import *
import os
root = Tk()
def Save():
fp = mypathEntry.get()
scribe = open('filepath.txt', 'w')
scribe.write(fp)
mypathEntry.delete(0, 'end')
mypathList.insert(1, fp)
def Open():
path = fp
menu = Menu(root)
##root.config(menu=menu)
##subMenu = Menu(menu)
##menu.add_cascade(label="Filepaths", menu=subMenu)
##subMenu.add_command(command=Save)
mypathLabel = Label(root, text="Copy and Paste your filepath here:")
mypathEntry = Entry(root, bg="black", fg="white", relief=SUNKEN)
mypathSaveButton = Button(root, text="Save Path", bg="black", fg="white", command=Save)
mypathList = Listbox(root, bg="black", fg="white")
mypathList.add_command(command=Open)
mypathLabel.pack()
mypathEntry.pack()
mypathSaveButton.pack()
mypathList.pack()
root.mainloop()
According to this,
http://effbot.org/tkinterbook/listbox.htm
The listbox item does not have a command option. So what you need to do instead is to bind an event to it. Here is a complete working example.
from tkinter import *
import os
root = Tk()
class MainGui:
def __init__(self, master):
self.mypathLabel = Label(master, text="Copy and Paste your filepath here:")
self.mypathEntry = Entry(master, bg="black", fg="white", relief=SUNKEN)
self.mypathSaveButton = Button(master, text="Save Path", bg="black", fg="white", command=self.save_path)
self.mypathList = Listbox(master, bg="black", fg="white")
self.mypathLabel.pack()
self.mypathEntry.pack()
self.mypathSaveButton.pack()
self.mypathList.pack()
self.mypathList.bind("<Double-Button-1>", self.open_path)
def save_path(self):
fp = self.mypathEntry.get()
self.mypathEntry.delete(0, 'end')
self.mypathList.insert(1, fp)
def open_path(self, event):
list_item = self.mypathList.curselection()
fp = self.mypathList.get(list_item[0])
print(fp)
try:
with open(fp, 'r') as result:
print(result.read())
except Exception as e:
print(e)
MainGui(root)
root.mainloop()

How to attribute a button the function to get text from an output file?

What I need is to make the view orders button to get the text from the Customer.txt file and set it inside a textfield i made.
#make order,cancel,view
from tkinter import *
import tkinter.messagebox
root = Tk()
file = open("Customer.txt", "w")
def textW():
outFile = open("Customer.txt", "wt")
def CancelOrder():
outFile=open("Customer.txt", "w")
outFile.write("")
tkinter.messagebox.showinfo("Cancel Order", "Your order has been canceled")
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
#tViewOrder.set(test)
print (test)
#test.set(tViewOrder)
#outFile.close()
def MakeOrder():
outFile=open("Customer.txt", "w")
outFile.write("" + tMakeOrder.get())
tkinter.messagebox.showinfo("Make Order", "Order has been placed. Thank you!")
#Labels
lMakeOrder = Label(root, text="Make an order")
lViewOrder = Label(root, text="View Order")
#TextFields
tMakeOrder = Entry(root)
tViewOrder = Entry(root, state="disabled")
#Buttons
bMakeOrder = Button(root, text="Make order",bg="black",fg="green", command=MakeOrder)
bCancelOrder = Button(root, text="Cancel order",bg="black",fg="green", command=CancelOrder)
bViewOrder = Button(root, text="View orders",bg="black",fg="green", command=ViewOrder)
#Position
lMakeOrder.grid(row=0)
lViewOrder.grid(row=1)
tMakeOrder.grid(row=0, column=2)
tViewOrder.grid(row=1, column=2)
bMakeOrder.grid(row=4)
bViewOrder.grid(row=4, column=2)
bCancelOrder.grid(row=4, column=4)
#Window stuff
root.title("Sky is a shit name service - Customer")
root.geometry("300x300")
root.mainloop()
You can put text inside your Entry by calling insert function on it.
MyEntry.insert(POSITION, TEXT)
Oh and one more thing. You can't insert anything in the entry if it's disabled.
So here is your modified function:
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
tViewOrder['state'] = 'normal'
tViewOrder.delete(0, 'end') #Remove everything before
tViewOrder.insert(0, test)
tViewOrder['state'] = 'disabled'
outFile.close()

Categories

Resources