NameError: name 'Frame' is not defined (Python) - python

I have constructed a messaging application, but it seems to have incorrect syntax:
from tkinter import messagebox
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(Frame):
def __init__(self, root=None):
Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
# Set configuration our frame
self.config(width = self.frame_width, height = self.frame_height, bg = color)
self.pack()
# Create textBox for input data
self.textbox_one = Text()
self.textbox_one.place(x = 30, y = 170, height = 200, width = 300 )
# Create textBox for result
self.textbox_two = Text()
self.textbox_two.place(x = 370, y = 170, height = 200, width = 300 )
label_input_text = Label( text = "Input text: ", bg = color)
label_input_text.place(x = 30, y = 155, height = 10, width = 70 )
During execution I get the following error:
Traceback (most recent call last):
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 11, in
class Application(Frame):
NameError: name 'Frame' is not defined
What might be the problem?

Frame is a class from the tkinter module.
To fix:
from tkinter import Frame
See an example in the official documentation: https://docs.python.org/3.7/library/tkinter.html#a-simple-hello-world-program
You also need to import Text and Label:
from tkinter import Frame
from tkinter import Text
from tkinter import Label
Or:
from tkinter import *
Here is how you can fix your code (I removed the unused imports):
import tkinter
color = 'lightblue' # color our background
class Application(tkinter.Frame):
def __init__(self, root=None):
super(Application, self).__init__(root)
self.frame_width = 700
self.frame_height = 400
# Set configuration our frame
self.config(width=self.frame_width, height=self.frame_height, bg=color)
self.pack()
# Create textBox for input data
self.textbox_one = tkinter.Text()
self.textbox_one.place(x=30, y=170, height=200, width=300)
# Create textBox for result
self.textbox_two = tkinter.Text()
self.textbox_two.place(x=370, y=170, height=200, width=300)
label_input_text = tkinter.Label(text="Input text: ", bg=color)
label_input_text.place(x=30, y=155, height=10, width=70)
root = tkinter.Tk()
app = Application(root)
app.mainloop()

Related

How to make my variable update based on cursor position?

I tried to build off of the solution here. My code is:
from tkinter import mainloop, Tk, Frame, Button, Label, Canvas, PhotoImage, NW
from tkinter import ttk
from tkinter import filedialog
import tkinter as tk
from PIL import Image, ImageTk
class my_class(tk.Tk):
def __init__(self):
super().__init__()
self.geometry=('1400x1400')
self.filename = ''
my_notebook = ttk.Notebook(self)
my_notebook.pack(pady=5)
self.selections = Frame(my_notebook, width = 1100, height = 700)
self.selections.pack(fill = "both", expand=1)
my_notebook.add(self.selections, text = "Selections")
Button(self.selections, text = "Select an Image", command = self.get_image).place(x=10,y=40)
self.image_frame = Frame(my_notebook, width = 1100, height = 700)
self.image_frame.pack(fill = "both", expand=1)
my_notebook.add(self.image_frame, text = "Image")
self.my_canvas = Canvas(self.image_frame, width=800, height=600, bg="white")
self.my_canvas.pack()
self.rgb_var = tk.StringVar(self.image_frame, '0 0 0')
self.rgb_label = tk.Label(self.image_frame, textvariable = self.rgb_var)
self.rgb_label.pack()
self.image_frame.bind('<Motion>', lambda e: self.get_rgb(e))
def get_image(self):
self.filename = filedialog.askopenfilename(initialdir="D:/Python", title="select a file", filetypes = (("png files","*.png"),("jpg files","*.jpg")))
self.img = Image.open(self.filename)
self.img_rgb = self.img.convert('RGB')
dim_x, dim_y = self.img_rgb.size
self.img_tk = ImageTk.PhotoImage(self.img_rgb.resize((dim_x, dim_y)))
self.my_canvas.create_image(dim_x // 2, dim_y // 2, image = self.img_tk)
def get_rgb(self, event):
x, y = event.x, event.y
try:
rgb = self.img_rgb.getpixel((x, y))
self.rgb_var.set(rgb)
except IndexError:
pass # ignore errors if cursor is outside the image
if __name__ == '__main__':
app = my_class()
app.geometry=('1200x900')
app.mainloop()
I can use the button to select an image. Then I click the (Image) tab and see the selected image on the canvas.
I expected the (rgb_var) displayed under the image to update as I move the mouse pointer across the image. Instead the numbers under the image only update when the mouse pointer is in the frame, but outside the canvas. Also the numbers displayed seem to be unrelated to pixels in the image. How can I display the RGB values of a pixel that is (under the mouse pointer) when the mouse pointer is over the image?

How to display image with upload button in and resize it with window resize (Dynamically)with Tkinter python, I need to add upload button

I need to add upload button so that I can upload the picture and display with this class. Everything working but when I am adding the upload button its giving me some error and my code is not wokring.
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.canvas = tk.Canvas(self.master)
self.canvas.pack()
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image)
self.loadbackground()
def loadbackground(self):
self.label = tk.Label(self.canvas, image = self.background)
self.label.bind('<Configure>',self.resizeimage)
self.label.pack(fill='both', expand='yes')
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((self.master.winfo_width(),self.master.winfo_height()))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()
Create the Button widget within the class constructor and bind it with self.loadbackground. Also, you don't need to recreate the Label widget every time instead use label.configure(image=yourimage).
Here is the code:
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.button = Button(self.master, text='Upload', command=self.loadbackground)
self.button.pack()
self.canvas = tk.Canvas(self.master)
self.canvas.pack(fill=BOTH, expand=True)
self.background_image = None
self.image_copy = None
self.background = None
self.label = tk.Label(self.canvas)
self.label.pack(fill='both', expand=True)
def loadbackground(self):
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image.resize((self.canvas.winfo_width(), self.canvas.winfo_height())))
self.label.configure(image=self.background)
self.label.bind('<Configure>',self.resizeimage)
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((event.width, event.height))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()

Image not seen in Tkinter (python) [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
I am starting to program, in which I have to make a python graphical interface, in which by means of a button the jpg file is chosen and it is displayed in the interface, but I have had a problem, since the image is not displayed and in the terminal it does not detect any error and practically I go crazy here I leave the code
from PIL import Image, ImageTk
from tkinter import Tk, Frame, Button, Label, Text, filedialog, PhotoImage
class Application_BotonPath(Frame):
def __init__(self, master = None):
super().__init__(master, width = "1300", height = "950", bg = "old lace")
self.master = master
self.pack()
self.Panel()
self.widget()
def Panel(self):
self.frame_side = Frame(self, width = '300', height = '850', bg = 'sky blue').place(x = 20, y = 50)
self.frame_show = Frame(self, width = '900', height = '850').place(x = 360, y = 50)
def widget(self):
boton = Button(self.frame_side, text = "Abrir Imagen", command = self.cargar_imagen).place(x = 85, y = 60, width = 150, height = 30)
salida = Text(self.frame_side, state = "disable").place(x = 43, y = 110, width = 250, height = 700)
def cargar_imagen(self):
self.ruta_imagen = filedialog.askopenfilename(title = "Abrir", filetypes = [('Archivo png', '*.png'), ('Archivo jpeg', '*.jpg')])
load = Image.open(self.ruta_imagen)
imagen = ImageTk.PhotoImage(load)
label = Label(self.frame_show, image = imagen)
label.place(x=0, y=0)
root = Tk()
root.wm_title("Detector de Caracteres")
app = Application_BotonPath(root)
app.mainloop()
image
This is what I get, the gray box that is in the upper right I suppose it is the image, but it does not show it. please help
Welcome to SO.
The image is created in a function, and when the function ends the reference to the image is garbage collected. Therefore the Label can not find any image.
You can save a reference to the image in the label object:
label = Label(self.frame_show, image = imagen)
label.image = imagen # Save reference to image
or you can make the reference an attribute of the instance:
self.imagen = ImageTk.PhotoImage(load)
label = Label(self.frame_show, image = self.imagen)

Getting missing required dependencies Numpy while using Pyinstaller

I have created a mini app that is used for combining a bunch of excel files, but I cant execute the exe due to this error. What I find strange is that I am not even using Numpy in my script. I have installed and reinstalled numpy, but that did not fix the issue.
I created a virtual environment which has the following libraries installed.
Error on Executing exe
Here is my code:
import tkinter as tk
from tkinter.simpledialog import askstring, askinteger
from tkinter.messagebox import showerror
from tkinter import messagebox
from tkinter import filedialog
from tkinter import ttk
import os
from os import path
import pandas as pd
import fnmatch
import glob
import datetime
from datetime import datetime
import time
import calendar
class Splash(tk.Toplevel):
def __init__(self, parent, width=0.8, height=0.6, useFactor=True):
tk.Toplevel.__init__(self, parent)
self.title("Splash")
w = 300
h = 200
x = 50
y = 100
self.geometry('%dx%d+%d+%d' % (w, h, x, y))
lbl = tk.Label(self,text="Combine Excel\n Version 1.0", bg = 'lightgrey' )
lbl.place(x=25, y=30)
self.master.overrideredirect(True)
self.lift()
## required to make window show before the program gets to the mainloop
self.update()
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.withdraw()
splash = Splash(self)
## simulate a delay while loading
time.sleep(1)
## finished loading so destroy splash
splash.destroy()
def getfiles():
listbox.delete(0,tk.END)
beginput = entry_1.get()
endinput = entry_2.get()
timefmt = "%m/%d/%y"
start = calendar.timegm(datetime.strptime(beginput, timefmt).timetuple())
end = calendar.timegm(datetime.strptime(endinput, timefmt).timetuple())
year = datetime.strptime(beginput, timefmt).strftime('%Y')
monthyr = datetime.strptime(beginput, timefmt).strftime('%m-%y') + ' Daily Collection'
yearmm = 'CA_LoanLvl_' + time.strftime("%Y%m%d")
yrnmsum = 'CA_Sum_' + time.strftime("%Y%m%d")
frame = pd.DataFrame()
list_ = []
cols = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,37,39,40,41,43,44,45,46,47,49,50,51,52,53,54,55,56,57]
path1 = path.join(r'\\corp.int\cms\DeptData\Monthly Reporting'
'\Daily Collection',year,monthyr,'Data')
pathexpt = path.join(r'\\corp.int\cms\DeptData\XX\DS\DataDownloads\Combine',yearmm)
pathexptsum = path.join(r'\\corp.int\cms\DeptData\XX\DS\DataDownloads\Combine',yrnmsum)
mypath = path1
def test(f):
if (not os.path.isfile(f)):
return 0
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(f)
return start<=ctime and end>=ctime
files = [f for f in glob.glob(os.path.join(mypath, "adv*")) if test(f)]
for item in files:
listbox.insert(tk.END, os.path.basename(item))
if __name__ == "__main__":
App()
# Create the main window
root = tk.Tk()
s = ttk.Style(root)
s.theme_use('clam')
root.title("Combine GNMA Files")
# set the root window's height, width and x,y position
# x and y are the coordinates of the upper left corner
w = 600
h = 400
x = 50
y = 100
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))
# use a colorful frame
frame = tk.Frame(root, bg='darkblue')
frame.pack(fill='both', expand='yes')
label = tk.Label(frame, text="Start Date-mm/dd/yy", bg = 'lightblue')
label.place(x=20, y=30)
label2 = tk.Label(frame, text="End Date-mm/dd/yy", bg = 'lightblue')
label2.place(x=20, y=100)
entry_1 = tk.Entry(root)
entry_1.place(x=20,y=60)
entry_2 = tk.Entry(root)
entry_2.place(x=20,y=130)
btn_1 = tk.Button(root,text="Get Files", bg='light grey', command = getfiles)
btn_1.place(x=400, y=15)
listbox = tk.Listbox(root)
listbox.place(x=20, y=160, width = 400)
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
If anyone runs across this, it seems it has to do with the version of Numpy that is causing errors with Pyinstaller. Take a look at the link below.
[How to fix 'Missing required dependencies ['numpy']' when running packaged app made with PyInstaller?

change Tkinter frame color with for loop from list of colors

I have the following code snippet. What i need to code that when i click the button i need the frame color to change one by one from the list of colors defined.
from tkinter import *
from tkinter import ttk
def ChangeColor():
colors = ['red','green', 'orange','blue']
for color in colors:
#color = entry.get()
frame.config(bg = color)
root = Tk()
root.title("Title")
frame = Frame (root, width = 260, height = 200)
frame.pack()
btn = ttk.Button(frame, text = 'Change color', command = ChangeColor)
btn.place (x = 80, y = 100)
entry = ttk.Entry (frame, width = 20)
entry.place(x = 80, y = 70)
root.mainloop()
You can use the cycle iterator from itertools for this.
from tkinter import *
from tkinter import ttk
from itertools import cycle
root = Tk()
root.title("Title")
frame = Frame (root, width = 260, height = 200)
frame.pack()
colors = ['red','green', 'orange','blue']
color_gen = cycle(colors)
def ChangeColor():
frame.config(bg = next(color_gen))
btn = ttk.Button(frame, text = 'Change color', command = ChangeColor)
btn.place (x = 80, y = 100)
entry = ttk.Entry (frame, width = 20)
entry.place(x = 80, y = 70)
root.mainloop()
One thing I need to mention: please avoid doing "star" imports. When you do
from tkinter import *
it puts 135 Tkinter names into your namespace; in Python 2 you get 175 names. This creates needless clutter in the namespace and it can cause name collisions: if you accidentally name one of your variables with one of the imported names that can lead to mysterious bugs. It's even worse when you do star imports with multiple modules since they can stomp over each others' names. Also, star imports make the code harder to read since you have to remember which names are defined locally and which are imported.
I would change your app to a class so you can store variables and access them easily, also I bound the enter key to the entry widget so that works too. This way when you create an instance of class app it is an instance of a Tk() root, but you don't have to call it root
import tkinter as tk
from tkinter import ttk
class app(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Title")
self.frame = tk.Frame(self, width = 260, height = 200)
self.frame.pack()
self.btn = ttk.Button(self.frame, text = 'Change color', command = self.ChangeColor)
self.btn.place (x = 80, y = 100)
self.entry = ttk.Entry (self.frame, width = 20)
self.entry.place(x = 80, y = 70)
self.entry.bind("<Return>",self.ChangeColorEntry)
self.colors = ['red','green','orange','blue']
self.current_color = -1
self.standard_bg = self.frame['background']
def ChangeColor(self,event=None):
if self.current_color == len(self.colors) - 1:
self.frame.config(bg = self.standard_bg)
self.current_color = -1
return
else:
self.current_color += 1
color = self.colors[self.current_color]
self.frame.config(bg = color)
def ChangeColorEntry(self,event=None):
entered = self.entry.get().lower().strip()
if entered == "none":
self.frame.config(bg = self.standard_bg)
else:
try:
self.current_color = self.colors.index(entered)
self.frame.config(bg = entered)
except:
pass
#PM 2Rings answer is cleaner but since I was working on this I thought I'd still post it incase you wanted to implement it manually
from tkinter import *
from tkinter import ttk
colors = ['red', 'green', 'orange', 'blue']
colors_it = iter(colors)
def get_next_color():
try:
global colors_it
return next(colors_it)
except StopIteration:
colors_it = iter(colors)
return next(colors_it)
def ChangeColor():
frame.config(bg=get_next_color())
root = Tk()
root.title("Title")
frame = Frame (root, width = 260, height = 200)
frame.pack()
btn = ttk.Button(frame, text = 'Change color', command = ChangeColor)
btn.place (x = 80, y = 100)
entry = ttk.Entry (frame, width = 20)
entry.place(x = 80, y = 70)
root.mainloop()

Categories

Resources