I made a program with a List and this List is included in the Combobox. I want to write the List into a file in order to read the List again later, even after a restart of the program.
I tried this:
import tkinter as tk
from tkinter import ttk
import pickle
# window
win = tk.Tk()
win.title("menu")
List = []
newList = []
with open('data.txt', 'wb') as f:
pickle.dump(List, f)
with open('data.txt', 'rb') as f:
newList = pickle.load(f)
# button click event
def clickMe():
List.append(name.get())
numberChosen.configure(values=List)
# text box entry
ttk.Label(win, text="Eingabe:").grid(column=0, row=0)
name = tk.StringVar()
nameEntered = ttk.Entry(win, width=12, textvariable=name)
nameEntered.grid(column=0, row=1)
# button
action = ttk.Button(win, text="Enter", command=clickMe)
action.grid(column=2, row=1)
# drop down menu
ttk.Label(win, text="Auswahl:").grid(column=1, row=0)
number = tk.StringVar()
numberChosen = ttk.Combobox(win, width=12)
numberChosen['values'] = [List]
numberChosen.grid(column=1, row=1)
win.mainloop()
You just need to save the list to the file after mainloop, and load it at the start of the program.
with open('data.txt', 'rb') as file:
data = pickle.load(file)
...
win.mainloop()
with open('data.txt', 'wb') as file:
pickle.dump(data, file)
This will load the list at the start, and save it after the tk window closes.
Related
Is there a way to restore the same previous session attributes in tkinter ? for example: having one button to restore the previous session attributes
Is there a way to set inputtxt to the value?
def restore():
file1 = open('user.txt', 'r')
Lines = file1.readlines()
unverified_file = Lines[0]
**inputtxt1.set(unverified_file)**
AttributeError: 'Text' object has no attribute 'set'
Looking at your updated code, you need insert not set. But first delete the entry -
def restore():
file1 = open('user.txt', 'r')
Lines = file1.readlines()
unverified_file = Lines[0]
inputtxt1.delete(0,'end')
inputtxt1.insert('end',unverified_file)
Also, take a look at this example -
import tkinter as tk
root = tk.Tk()
def save():
a = entry1.get()
b = entry2.get()
with open('1.txt','w') as f:
f.write(a)
f.write('\n')
f.write(b)
def restore():
with open('1.txt','r') as f:
text = f.read().split('\n')
entry1.insert('end',text[0])
entry2.insert('end',text[1])
entry1 = tk.Entry(root)
entry1.pack()
entry2 = tk.Entry(root)
entry2.pack()
button1 = tk.Button(root,text='Save Results',command=save)
button1.pack()
button2 = tk.Button(root,text='Restore Previous Results',command=restore)
button2.pack()
root.mainloop()
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.
This GUI allows the user to open the file browser and select the files you need, show it on the field blank and then open the file once open is pressed. I'm new to python and had tried placing print tkFileDialog.askopenfilename() at the self.filename but this results in a syntax error. Please help. Thanks!
My question is as follows:
1) Why does my file browser open twice upon pressing the "file browser" button.
2) Also, how do I state the directory of the file selected in the file blank instead of in the python command prompt?
I would like to open the file in the future after pressing the ok button.
from Tkinter import *
import csv
import tkFileDialog
class Window:
def __init__(self, master):
self.filename=""
csvfile=Label(root, text="Load File:").grid(row=1, column=0)
bar=Entry(master).grid(row=1, column=1)
#Buttons
y=12
self.cbutton= Button(root, text="OK", command=self.process_csv) #command refer to process_csv
y+=1
self.cbutton.grid(row=15, column=3, sticky = W + E)
self.bbutton= Button(root, text="File Browser", command=self.browsecsv) #open browser; refer to browsecsv
self.bbutton.grid(row=1, column=3)
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
print tkFileDialog.askopenfilename() # print the file that you opened.
def callback():
abc = askopenfilename()
execfile("input.xlsx")
def process_csv(self):
if self.filename:
with open(self.filename, 'rb') as csvfile:
logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
rownum=0
for row in logreader:
NumColumns = len(row)
rownum += 1
Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)]
root = Tk()
window=Window(root)
root.mainloop()
Your both questions are connected. The problem is in your browsecsv(self) method. Your directory is already stored in self.filename, no need to call askopenfilename() again. That's the reason why the file browser opens twice. Moreover, to set text in your Entry, you need to assign it a text variable.
self.entryText = StringVar()
self.bar = Entry(root, textvariable=self.entryText ).grid(row=1, column=1)
Then, you can assign it to the Entry in your method:
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
self.entryText.set(self.filename)
In tkinter, python, I'm creating an info like text editor that uses StringVar() to display a file, also, with the use of entry and a button, I created a delete button, which deletes a certain line in a file. The problem I have is that the file does not delete the specified line and it does not update to show the file's contents. Here's my code:
from tkinter import *
root = Tk()
root.title("text")
root.geometry("700x700")
file = open(r"info.txt", "r")
lines = file.readlines()
file.close()
strd = StringVar()
def updatestr():
fileread = open(r"info.txt", "r")
lines2 = fileread.readlines()
strd.set("{}".format(lines2))
root.after(1, updatestr)
fileread.close()
updatestr()
lads = Label(root, textvariable=strd)
lads.pack()
blank = Label(root, text="")
blank.pack()
blank = Label(root, text="")
blank.pack()
blank = Label(root, text="")
blank.pack()
entry = Entry(root)
entry.configure(width=9)
entry.pack()
def DeleteEntry():
global file
file = open(r"info.txt", "w")
global lines
for line in lines:
if line!="{}".format(entry.get())+"\n":
file.write(line)
file.close()
confent = Button(root, text="Delete", command=DeleteEntry)
confent.configure(width=7)
confent.pack()
Not sure why this is happening, so I'd appreciate some help :)
Thanks
I'm doing some work with GUI in python. I'm using the Tkinter library.
I need a button, which will open a .txt file and do this bit of processing:
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
I started with:
from Tkinter import *
import tkFileDialog,Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
def openFile():
fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
Button(root, text = 'Open .txt file', fg = 'black', command= openFile).pack(**button_opt)
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
root.mainloop()
Now I don't know how to assemble my code so it runs when the button is pressed.
The main problem was tkFileDialog.askopenfile() returns an open file rather than a file name. This following seemed to be more-or-less working for me:
from Tkinter import *
import tkFileDialog, Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
def openFile():
f_in = tkFileDialog.askopenfile(
parent=root,
title="Open .txt file",
filetypes=[("txt file",".txt"),("All files",".*")])
frequencies = collections.defaultdict(int)
for line in f_in:
for char in line:
frequencies[char] += 1
f_in.close()
total = float(sum(frequencies.values()))
print 'total:', total
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
Button(root, text = 'Open .txt file',
fg = 'black',
command= openFile).pack(**button_opt)
root.mainloop()
For quickly creating simple GUI programs I highly recommend EasyGUI, a fairly powerful yet simple Tk--based Python module for doing such things.
Try something laid out a bit like this:
class my_app():
def __init__():
self.hi_there = Tkinter.Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=Tkinter.LEFT)
def say_hi():
# do stuff
You also may want to read:
This tutorial on Tkinter,
And this one.
EDIT: The OP wanted an example with his code (I think) so here it is:
from Tkinter import *
import tkFileDialog,Tkconstants,collections
class my_app:
def __init__(self, master):
frame = Tkinter.Frame(master)
frame.pack()
self.button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
self.button = Button(frame, text = 'Open .txt file', fg = 'black', command= self.openFile).pack(**button_opt)
self.calc_button = Button(frame, text = 'Calculate', fg = 'black', command= self.calculate).pack()
self.fileName = ''
def openFile():
fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
def calculate():
############################################### *See note
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
################################################
root = Tk()
app = App(root)
root.title("TEST")
root.geometry("800x600")
root.mainloop()
*Note: Nowhere in your code did I see where collections came from so I wasn't quite sure what to do with that block. In this example I have set it to run on the
In your openFile() function, just after you ask the user for a file name, put your code!