I want to use the variable (file) in class (PageOne) I'm not good in python so even when I did my research I couldn't do it, can you help me please ? My project is to take a csv file from the user(in WelcomePage) and it will pick a random row from that file and show it in (PageOne).
i tried different ways but always the same error message (name 'file' is not defined)
from cProfile import label
import tkinter as tk
from turtle import title
from typing import Container
from tkinter import font as tkfont
from tkinter.filedialog import askopenfile
class MainFrame (tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
self.titlefont = tkfont.Font(family = 'Verdana',size=12,
weight = "bold", slant='roman')
container =tk.Frame()
container.grid(row=0, column=0, sticky='nesw')
self.id =tk.StringVar()
self.id.set("Mister")
self.listing = {}
for p in (WelcomePage, PageOne):
page_name = p.__name__
frame = p(parent = container, controller = self)
frame.grid(row=0, column=0, sticky='nesw')
self.listing[page_name] = frame
self.up_frame('WelcomePage')
def up_frame(self,page_name):
page = self.listing[page_name]
page.tkraise()
class WelcomePage(tk.Frame):
global file
def open_file():
file = askopenfile(mode='r', filetypes=[('I', '*csv')])
if file is not None:
pass
return file
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.id = controller.id
label = tk.Label(self,text= "Welcome Page \n" controller.id.get(),
font= controller.titlefont)
label.pack()
lod = tk.Button (self, text="Select a file",
command= lambda:open_file())
lod.pack()
bou = tk.Button (self, text="Submit",
command= lambda: controller.up_frame("PageOne"))
bou.pack()
class PageOne(WelcomePage,tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.id = controller.id
label = tk.Label(self,text= "Page One \n" controller.id.get(),
font= controller.titlefont)
label.pack()
bou = tk.Button (self, text="back to main",
command= lambda: controller.up_frame("WelcomePage"))
bou.pack()
if __name__ == '__main__':
app = MainFrame()
app.mainloop()
CodePudding user response:
try this -- use the keyword global in the method as well for the variable purpose
then your error of file name is not defined should resolved.
def open_file():
global file
file = askopenfile(mode='r', filetypes=[('I', '*csv')])
if file is not None:
pass
return file
CodePudding user response:
In Python 3.8 used Walrus. Put keyword inside function
Before:
def open_file():
file = askopenfile(mode='r', filetypes=[('I', '*csv')])
if file is not None:
pass
return file
After Walrus:
def open_file():
global file
if (file := askopenfile(mode='r', filetypes=[('I', '*py' is not None)])):
pass
return file