python tkinter to display File and Save - python

I have created an coding gui,which doesnot show 'File' and 'save' in the Gui
Please help me to fix my problem.
I have created a Function for File and Save ,still not working!
please help me to rectify my code!
from tkinter import *
import tkinter.messagebox
import tkinter
import tkinter as tki
import tkinter.filedialog as th1
import re
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
# create first Text label, widget and scrollbar
self.lbl1 = tki.Label(txt_frm, text="Type")
self.lbl1.grid(row=0,column=0,padx=2,pady=2)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
scrollb1.grid(row=0, column=2, sticky='nsew')
self.txt1['yscrollcommand'] = scrollb1.set
button = tki.Button(txt_frm,text="Clickone", command = self.retrieve_input)
button.grid(column=2,row=0)
button1 = tki.Button(txt_frm,text="Cli", command = self.clearBox)
button1.grid(column=2,row=0)
def retrieve_input(self):
input1 = self.txt1.get("0.0",'end-1c')
with open('text.txt','a+') as f:
f.write(input1+'\n')
f.close()
def clearBox(self):
self.txt1.delete('1.0', 'end')#<-0.0/1.0
def file_save():
f = th1.asksaveasfile(mode='w', defaultextension=".txt")
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
text2save = str(text.get(1.0, END))
a= (f)
f.write(text2save)
f.close()
root = tki.Tk()
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="Save", command=file_save)
app = App(root)
root.mainloop()
Please help!Answers will be appreciated!

You aren't adding the menubar to the window. Add this after you create the menubar.
root.configure(menu=menubar)
You then also have to add the file menu to the menubar:
menubar.add_cascade(label="File", menu=filemenu)

Related

python tkinter entry can not get value from askdirectory

I created a tkinter program of pop new windows to do something.when I ran it,there are two problems.The first problem is poping two windows when click "1、reset chanel".I checked over and over,but the problem is still over there.The second problem is about the 'Entry' value.I want it to show the askdirectory value.Whatever I done,it is still empty.
Here is the code,any help is appreciated.
import tkinter as tk
from tkinter import filedialog, dialog
from tkinter.filedialog import askdirectory
from tkinter.messagebox import *
class SgyChan(tk.Toplevel):
def __init__(self):
super().__init__()
self.setup_UI()
def open_bigspsfile(self):
self.filebig_path = filedialog.askopenfilename()
self.bigpath.set(self.filebig_path)
print(self.filebig_path)
def open_litspsfile(self):
self.filelit_path = askdirectory() #
self.litpath.set(self.filelit_path)
print(self.filelit_path)
def getValueBig(self):
self.filebig_path=self.entry1.get()
return self.filebig_path
def getValueLit(self):
self.filelit_path=self.entry2.get()
return self.filelit_path
def mat_file(self):
spspath=self.getValueBig()
watchdir=self.getValueLit()
print('working......')
def setup_UI(self):
root = tk.Tk()
root.geometry('500x100+600+300')
root.title('sgy change chan')
self.bigpath= tk.StringVar()
self.litpath= tk.StringVar()
label1 = tk.Label(root, text="1、sps file:")
label2 = tk.Label(root, text="2、sgy :")
label1.grid(row=0)
label2.grid(row=1)
self.entry1 = tk.Entry(root,width=40,textvariable = self.bigpath)
self.entry2 = tk.Entry(root, width=40,textvariable = self.litpath)
self.entry1.grid(row=0, column=1)
self.entry2.grid(row=1, column=1)
buttonForFile = tk.Button(root, text="browser files", command=self.open_bigspsfile)
buttonRun = tk.Button(root, text="browser directory", command=self.open_litspsfile)
buttonForFile.grid(row=0, column=2)
buttonRun.grid(row=1, column=2)
buttonMatch = tk.Button(root, text="3、data process", command=self.mat_file)
buttonMatch.grid(row=4, column=1)
class MyApp(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('500x145+400+100')
self.title('sgy tools')
self.setupUI()
def setupUI(self):
row1 = tk.Frame(self)
row1.pack(fill="x")
buttonForFile = tk.Button(row1, text="1、reset chanel", command=SgyChan)
buttonForFile.grid(row=0, column=2)
if __name__ == '__main__':
app = MyApp()
app.mainloop()

Its giving me a module not found error but its installed but if i run a different code it does not give a error

When I run this code it gives a module not found error for line 2 but it is installed
on my computer. I know that because when i type pip list in the command prompt it is in the list
from tkinter import *
from tkvideoplayer import TkinterVideo
from tkinter.filedialog import askopenfile
window = Tk()
window.title("My Video Player")
window.geometry("500x500")
window.config(bg="Turquoise")
heading = Label(window, text="My Video Player", bg="Orange Red", fg="white", font="4 none bold")
heading.config(anchor=CENTER)
def openFile():
file = askopenfile(mode="r", filetypes=[('Video Files', '*.mp4', '*.mov')])
if file is not None:
global filename
filename = file.name
global videoPlayer
videoPlayer = TkinterVideo(master=window, scaled=True, pre_load=False)
videoPlayer.load(r"{}".format(filename))
videoPlayer.pack(expand=True, fill="both")
videoPlayer.play()
def playFile():
videoPlayer.play()
def stopFile():
videoPlayer.stop()
def pauseFile():
videoPlayer.pause()
openbtn = Button(window, text="Open", command=lambda: openFile())
stopbtn = Button(window, text="Stop", command=lambda: stopFile())
playbtn = Button(window, text="Play", command=lambda: playFile())
pausebtn = Button(window, text="Pause", command=lambda: pauseFile())
openbtn.pack(side=TOP, pady=2)
stopbtn.pack(side=TOP, pady=4)
playbtn.pack(side=TOP, pady=3)
pausebtn.pack(side=TOP, pady=5)
heading.pack()
window.mainloop()
However on the same computer if I run this code
import datetime
import tkinter as tk
from tkinter import filedialog
from tkVideoPlayer import TkinterVideo
def update_duration(event):
""" updates the duration after finding the duration """
end_time["text"] = str(datetime.timedelta(seconds=vid_player.duration()))
progress_slider["to"] = vid_player.duration()
def update_scale(event):
""" updates the scale value """
progress_slider.set(vid_player.current_duration())
def load_video():
""" loads the video """
file_path = filedialog.askopenfilename()
if file_path:
vid_player.load(file_path)
progress_slider.config(to=0, from_=0)
progress_slider.set(0)
play_pause_btn["text"] = "Play"
def seek(value):
""" used to seek a specific timeframe """
vid_player.seek(int(value))
def skip(value: int):
""" skip seconds """
vid_player.skip_sec(value)
progress_slider.set(progress_slider.get() + value)
def play_pause():
""" pauses and plays """
if vid_player.is_paused():
vid_player.play()
play_pause_btn["text"] = "Pause"
else:
vid_player.pause()
play_pause_btn["text"] = "Play"
def video_ended(event):
""" handle video ended """
progress_slider.set(progress_slider["to"])
play_pause_btn["text"] = "Play"
root = tk.Tk()
root.title("Video Player")
root.geometry("700x600")
load_btn = tk.Button(root, text="Load", command=load_video)
load_btn.pack()
vid_player = TkinterVideo(scaled=True, pre_load=False, master=root)
vid_player.pack(expand=True, fill="both")
play_pause_btn = tk.Button(root, text="Play", command=play_pause)
play_pause_btn.pack()
skip_plus_5sec = tk.Button(root, text="Skip -5 sec", command=lambda: skip(-5))
skip_plus_5sec.pack(side="left")
start_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
start_time.pack(side="left")
progress_slider = tk.Scale(root, from_=0, to=0, orient="horizontal", command=seek)
progress_slider.pack(side="left", fill="x", expand=True)
end_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
end_time.pack(side="left")
vid_player.bind("<<Duration>>", update_duration)
vid_player.bind("<<SecondChanged>>", update_scale)
vid_player.bind("<<Ended>>", video_ended)
skip_plus_5sec = tk.Button(root, text="Skip +5 sec", command=lambda: skip(5))
skip_plus_5sec.pack(side="left")
root.mainloop()
It works and does not give an error.
But I am using the same code line.
Can anyone explain that?
But I am using the same code line.
No, you're not. The working version spells tkVideoPlayer in camelCase (and indeed, according to the package's docs that's the correct casing):
from tkVideoPlayer import TkinterVideo
and the version that doesn't work spells it in all lowercase.
from tkvideoplayer import TkinterVideo
You'll have to be careful about character case; in general programming languages and environments aren't forgiving about that.

tkinter TopLevel destroy raising AttrbuteError

I'm writing a multi-window GUI in tkinter. Clicking on the 'Load CSV Data' button in the the Main Window creates an instance of the LoadWindow class which inherits from tkinter.TopLevel and the MainGui instance is passedto LoadWindow since I want to manipulate it from LoadWindow. However when I call self.destroy to close the Load CSV window when the Load CSV button is clicked, I get the following error even though the Load CSV data window closes.
if self._name in self.master.children:
AttributeError: 'MainGUI' object has no attribute 'children'
Below is the code:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import os
import pandas as pd
class MainGUI:
def __init__(self, master):
self.master = master
master.title("Main Window")
master.geometry("700x500")
# create all elements in main window
load_csv_button = ttk.Button(master,
text='Load CSV Data',
command=lambda: LoadWindow(master=self))
load_db_button = ttk.Button(master, text='Load from Database')
save_db_button = ttk.Button(master, text='Save Current File to Database')
data_transform_button = ttk.Button(master, text='Data Transformation')
data_analysis_button = ttk.Button(master, text='Data Analysis')
#update later
preview_df_button = ttk.Button(master, text='Preview Data Frame',
command=lambda: print(self.main_df))
self.text_box = tk.Text(master, bg='grey')
# insert welcome message into text box and disable
self.text_box.insert(tk.END, 'Welcome to the Data Analysis Hub')
self.text_box.config(state='disabled')
# snap all elements to grid
load_csv_button.grid(row=0, column=1, sticky='NSEW')
load_db_button.grid(row=1, column=1, sticky='NSEW')
save_db_button.grid(row=2, column=1, sticky='NSEW')
data_transform_button.grid(row=0, column=2, sticky='NSEW')
data_analysis_button.grid(row=1, column=2, sticky='NSEW')
preview_df_button.grid(row=2, column=2, sticky='NSEW')
self.text_box.grid(row=4, column=1, columnspan=2)
self.main_df = None
def update_textbox(self, message):
self.text_box.config(state='normal')
self.text_box.delete('1.0', 'end')
self.text_box.insert(tk.END, message)
self.text_box.config(state='disabled')
class LoadWindow(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self)
self.title("Load CSV")
self.geometry("200x200")
self.master = master
# get csvs in current directory
listbox = tk.Listbox(self, selectmode=tk.SINGLE)
csv_files = self.find_csv_files(os.getcwd())
for csv in csv_files:
listbox.insert(tk.END, csv)
listbox.grid(row=1, column=1, columnspan=3, sticky='NSEW')
# assign selected csv to maindf
active = listbox.get(tk.ACTIVE)
load_csv_button = ttk.Button(self, text='Load CSV',
command=lambda: self.load_selected(active))
load_csv_button.grid(row=2, column=1)
def find_csv_files(self, path):
# Check for csvs in path
filenames = os.listdir(path)
csv_files = [x for x in filenames if x.endswith('.csv')]
return csv_files
def load_selected(self, active):
try:
csv_path = os.getcwd()+"/"+active
main_df = pd.read_csv(csv_path)
# update maingui variable
self.master.main_df = main_df
# update maingui status on df loaded
self.master.update_textbox(f'{active} loaded as DataFrame')
self.destroy()
except pd.errors.ParserError:
error = 'Looks like you either have no csvs in working directory ' \
'or loaded a file that is not a csv, please try another file'
messagebox.showerror(title='Load error', message=error)
if __name__ == '__main__':
window = tk.Tk()
maingui = MainGUI(window)
window.mainloop()
Start with this line:
LoadWindow(master=self)
self is not a window. Inside the __init__ you do self.master = master. Thus, self.master inside of LoadWindow is not a widget and thus it has no children attribute.
You need to change how you create LoadWindow to be something like this:
LoadWindow(master=self.master)

I'm importing a module to another module to make a treeview in tkinter but it is showing me a error NameError: name 'treeview' is not defined

I am trying to import a function add() from module tab.py to a module treeimport.py to create a treeview widget after taking data from user in module treeimport.py and insert that data in the treeview widget im module tab.py after a button ADD is clicked having function add() but it is showing me a error
NameError: name 'treeview' is not defined
The module tab.py is below
from tkinter import ttk
from tkinter import *
window = Tk()
def tree():
col = ('Website','Email','Password','Security check')
treeview = ttk.Treeview(window, height=5, show='headings', columns=col)
treeview.column('Website', width=100, anchor=CENTER)
treeview.column('Email', width=100, anchor=CENTER)
treeview.column('Password', width=100, anchor=CENTER)
treeview.column('Security check', width=100, anchor=CENTER)
treeview.heading('Website', text='Website')
treeview.heading('Email', text='Email')
treeview.heading('Password', text='Password')
treeview.heading('Security check', text='Security check')
treeview.pack(side=TOP, fill=BOTH)
def add():
treeview.insert('', 'end',values=(website.get(), email.get(), passwd.get(), 'YES'))
window.mainloop()
And treeimport module is below:
from tkinter import ttk
from tkinter import *
from tab import *
ask = Tk()
website = Entry(ask)
email = Entry(ask)
passwd = Entry(ask)
website.pack()
email.pack()
passwd.pack()
rec = Button(ask,text='ADD', command = add())
rec.pack()
ask.mainloop()
Please help me with this problem.
Here, I have actually reduced the use of importing an external file and compiled it all to a single code, and it works fine. I have used some.txt make sure to create such an empty file before trying this code out.
from tkinter import ttk
from tkinter import *
ask = Tk()
def tree():
window = Toplevel(ask)
col = ('Website','Email','Password','Security check')
treeview = ttk.Treeview(window, height=5, show='headings', columns=col)
treeview.column('Website', width=100, anchor=CENTER)
treeview.column('Email', width=100, anchor=CENTER)
treeview.column('Password', width=100, anchor=CENTER)
treeview.column('Security check', width=100, anchor=CENTER)
treeview.heading('Website', text='Website')
treeview.heading('Email', text='Email')
treeview.heading('Password', text='Password')
treeview.heading('Security check', text='Security check')
treeview.pack(side=TOP, fill=BOTH)
#opening the list
open_file = open('some.txt','r')
lines = open_file.readlines()
#populating the list from the file
for line in lines:
treeview.insert('', 'end',values=line)
def store():
#creating a list of data to be stored in file
vals = [website.get()+' ',email.get()+' ',passwd.get()+' ','Yes\n']
lines = open('some.txt','a')
lines.writelines(vals)
#clearing the entry boxes
website.delete(0,END)
email.delete(0,END)
passwd.delete(0,END)
#setting focus back on first window
website.focus_force()
website = Entry(ask)
email = Entry(ask)
passwd = Entry(ask)
website.pack()
email.pack()
passwd.pack()
rec = Button(ask,text='ADD', command=store)
rec.pack()
view = Button(ask,text='VIEW',command=tree)
view.pack()
ask.mainloop()
some.txt
www.google.com something#gmail.com stackoverflow Yes
Do let me know if any errors or doubts.
Cheers
I got a solution.
But i want to make the addition of data in treeview a backend task, which i am searching for.
from tkinter import ttk
from tkinter import *
window = Tk()
ask = Toplevel()
website = Entry(ask)
email = Entry(ask)
passwd = Entry(ask)
website.pack()
email.pack()
passwd.pack()
col = ('Website','Email','Password','Security check')
treeview = ttk.Treeview(window, height=5, show='headings', columns=col)
treeview.column('Website', width=100, anchor=CENTER)
treeview.column('Email', width=100, anchor=CENTER)
treeview.column('Password', width=100, anchor=CENTER)
treeview.column('Security check', width=100, anchor=CENTER)
treeview.heading('Website', text='Website')
treeview.heading('Email', text='Email')
treeview.heading('Password', text='Password')
treeview.heading('Security check', text='Security check')
treeview.pack(side=TOP, fill=BOTH)
def add():
treeview.insert('', 'end',values=(website.get(), email.get(), passwd.get(), 'YES'))
rec = Button(ask,text='ADD', command = add)
rec.pack()
ask.mainloop()
window.mainloop()

Cant get listbox to show for tkinter

So, what I am trying to do is open a file when pressing a button and displaying the contents in a listbox. This is what I have so far, but I am not getting the listbox to display, let alone get the info to be in the listbox:
#!/usr/bin/perl -w
import time
from Tkinter import *
import tkFileDialog
def listbox(listbox):
def open_file():
file = tkFileDialog.askopenfilename()
openFile = open(file)
for line in openFile:
listbox.insert(END, line)
open_file()
class App:
def __init__(self, parent):
frame = Frame(parent.title("Buttons"))
frame.pack()
root.pack_propagate(0)
self.exit = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.exit.pack(side=LEFT)
self.open = Button(frame, text="Open...", command=self.call_listbox)
self.open.pack(side=LEFT)
frame.listbox = Frame()
scrollme = Scrollbar(frame.listbox)
self.listbox = Listbox(frame.listbox, yscrollcommand = scrollme.set)
scrollme.config(command = self.listbox.yview)
scrollme.pack(side = RIGHT, fill = Y)
self.listbox.pack()
self.listbox.insert(END, "Code:")
def call_listbox(self):
listbox(self.listbox)
root = Tk()
app = App(root)
root.mainloop()
any suggestions? thanks
You are forgetting to pack the frame that contains the listbox.
FWIW, your overloading of the name "listbox" makes your code very confusing - you have def listbox(listbox), self.listbox and frame.listbox. And you also have call_listbox and the Listbox class to add to the confusion.

Categories