Cannot create 2 treeview in same window/ Tkinter - python

when I tried to create 2 treeview inside same window in tkinter , i got an error like this
File "D:\Anaconda Navigator\lib\tkinter\ttk.py", line 1240, in column
return _val_or_dict(self.tk, kw, self._w, "column", column) File
"D:\Anaconda Navigator\lib\tkinter\ttk.py", line 298, in _val_or_dict
res = tk.call(*(args + options)) _tkinter.TclError: Invalid column
index PID.
The reason i got this error is that because I have created another treeview above and the one that i am creating later has different column names and spyder cannot differentiate them.
Thanks for your help.
The error i got is this:
my code is
class swindow:
def __init__(self, window):
#Settings For Supplier Window
self.window = window
self.window.title('TEDARİKÇİLER')
self.window.state('zoomed')
self.window.protocol("WM_DELETE_WINDOW", on_closing)
#Frames for treeview and data entry
self.view = Frame(self.window)
self.viewr =Frame(self.window,bg = 'red')
self.entry= Frame(self.window)
self.rentry = Frame(self.window)
#Labels
self.sheading = Label(self.entry , text = 'Tedarikçi Girişi', font = ('Verdana',17,'bold'),fg = 'blue')
self.sname = Label(self.entry,text = 'Tedarikçi Adı: ', font=('Verdana',12),width =18)
self.sphone = Label(self.entry, text = 'Tedarikçi Tel: ', font=('Verdana',12),width = 18)
self.smail= Label(self.entry, text = 'Tedarikçi Mail Adresi: ', font=('Verdana',12),width=18)
self.sofficer = Label(self.entry, text = 'İlgili Adı: ',font = ('Verdana',12), width =18)
self.headingr = Label(self.rentry,text = 'Tedarik Edilmiş Parça Girişi',font = ('Verdana',17,'bold'),fg = 'red')
self.snamer = Label(self.rentry,text = 'Tedarikçi Adı: ',font = ('Verdana',12), width =18)
self.pnamer = Label(self.rentry,text = 'Parça Adı: ',font = ('Verdana',12), width =18)
self.pbrandr = Label(self.rentry,text = 'Parça Markası: ',font = ('Verdana',12), width =18)
self.quantity = Label(self.rentry,text = 'Parça Adet: ' ,font = ('Verdana',12), width =18)
self.pricer = Label(self.rentry,text = 'Parça Fiyat: ',font = ('Verdana',12), width =18)
#EntryBoxes
self.nameentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.phoneentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.mailentry = Entry(self.entry , width=20 , font = ('Verdana',12))
self.officerentry = Entry(self.entry , width=20 , font = ('Verdana',12))
#ComboBoxes and EntryBoxes for Part-Supplier Relationship
self.scombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.pcombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.bcombo = ttk.Combobox(self.rentry, width = 20, font = ('Verdana',12))
self.quantityentry = Entry(self.rentry,width = 22,font=('Verdana',12))
self.priceentry = Entry(self.rentry,width = 22,font=('Verdana',12))
#Buttons
self.backbutton = Button(self.window,text='Ana Pencere',font=('Verdana',14), command = self.goback)
self.add = Button(self.entry , text = 'Tedarikçi Ekle',font= ('Verdana',12), bg='chartreuse1',command = self.add_supplier)
self.update = Button(self.entry , text = 'Tedarikçi Güncelle', font= ('Verdana',12),bg='yellow',command = self.update_supplier)
self.delete = Button(self.entry ,text= 'Tedarikçi Sil', font= ('Verdana', 12),bg='red',command = self.delete_supplier)
self.addr = Button(self.rentry,text = 'Tedarikçi-Parça Ekle',font= ('Verdana',12), bg='chartreuse1',command = self.addr)
self.updater = Button(self.rentry,text = 'Tedarikçi-Parça Güncelle', font= ('Verdana',12),bg='yellow',command = self.updater)
#ScrollBar For Treeview
self.scroll = Scrollbar(self.view)
self.yscrollr = Scrollbar(self.viewr)
#Treeview for Supplier Table
self.tree = ttk.Treeview(self.view, yscrollcommand= self.scroll.set, selectmode = 'browse')
self.tree['columns'] = ('SID','SuppName', 'PartName','PartNo','Part Price')
self.headings=['sid','Tedarikçi Adı','Parça Adı','Parça No','Parça Fiyat']
self.tree.column('#0', width= 0, stretch= NO)
for i,j in zip(self.tree['columns'], self.headings):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
self.tree['displaycolumns'] = ('SuppName', 'PartName','PartNo','Part Price')
#Treeview for Supplier-Part Relation
self.treer = ttk.Treeview(self.viewr , yscrollcommand = self.yscrollr.set, selectmode = 'browse')
self.treer['columns'] = ('SID','PID','Sname','Pname','Pcategory','Squantity','Sdate','Sprice','Pbrand','Ptype')
self.headingsr = ['sid','pid','Tedarikçi Adı','Parça Adı','Parça Kategorisi','Tedarik Edilen Adet','Tedarik Tarihi','Tedarik Fiyatı','Parça Markası','Parça Hammaddesi']
self.treer.column('#0', width = 0, stretch = NO)
for i,j in zip(self.treer['columns'],self.headingsr):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
self.treer['displaycolumns'] = ('Sname','Pname','Pcategory','Pbrand','Ptype','Squantity','Sdate','Sprice')
#Binding Treeview to ScrollBar
self.tree.bind('<Double-1>', self.selector)
self.scroll.config(command = self.tree.yview)
#Placement of Frames
self.entry.place_configure(x=45,y=30,height= 293, width=475)
self.view.place_configure(width=950,height =256,x=530,y=55)
self.viewr.place_configure(width =950,height=350,x = 530, y=362)
self.rentry.place(x=45 , y = 350, height = 410, width =475)
#Placement of Labels
self.sheading.pack(fill = X)
self.sname.place(x=15 , y=45)
self.sphone.place(x=15 , y=100)
self.smail.place(x=15 , y=155)
self.sofficer.place(x=15 , y=210)
self.headingr.place(x= 49,y=0)
self.snamer.place(x= 5,y=45)
self.pnamer.place(x = 5, y = 100)
self.pbrandr.place(x = 5, y = 155)
self.quantity.place(x = 5, y = 210)
self.pricer.place(x = 5, y = 265)
#Placement of ComboBoxes
self.scombo.place(x =200 , y =45 )
self.pcombo.place(x =200 , y =100 )
self.bcombo.place(x = 200, y = 155)
#Placement of EntryBoxes
self.nameentry.place(x=210, y=45)
self.phoneentry.place(x=210 , y=100)
self.mailentry.place(x=210 , y=155)
self.officerentry.place(x=210, y=210)
self.quantityentry.place(x =200 , y =210 )
self.priceentry.place(x = 200, y = 265)
#Placement of Buttons
self.backbutton.place(x=650,y= 0)
self.add.place(x=15,y=250)
self.update.place(x=150,y=250)
self.delete.place(x=325,y=250)
self.addr.place(x = 0,y = 305 )
self.updater.place(x = 210 ,y =305 )
#Placement of Treeview
self.tree.place(x=0, y=40,height =700, width=933)
self.treer.place(x=0,y=40,height = 700,width=933)
#Placement of ScrollBar
self.scroll.pack(side = RIGHT, fill = Y)
self.window.mainloop()

You used self.tree in the for loop:
for i,j in zip(self.treer['columns'],self.headingsr):
self.tree.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.tree.heading(i,text = j, anchor = CENTER)
But it should be self.treer instead:
for i,j in zip(self.treer['columns'],self.headingsr):
# should use self.treer instead of self.tree
self.treer.column(i,anchor= CENTER,width= 150, minwidth= 150)
self.treer.heading(i,text = j, anchor = CENTER)
Suggest to go through your code and make sure you use the correct instance variable: self.tree or self.treer.

Related

Why is my Tkinter button command ignoring the arguments I'm sending into a function?

I'm attempting to create a GUI for astrophotography, and am trying to add a function that would allow choosing a specific directory for files. I'm using a button with a command, and am trying to run the function (that has an argument) using the lambda function. However, trying to run it I was given a TypeError: uploadFlats() missing 1 required positional argument: 'x'.
class Astrophotography:
def __init__(self):
self.mainWin = tk.Tk()
self.mainWin.title("Automatic Image Editor")
self.firstFrame = tk.Frame(self.mainWin, width = 600, height = 200)
self.secondFrame = tk.Frame(self.mainWin)
self.thirdFrame = tk.Frame(self.mainWin)
# First Frame
self.description = tk.Label(self.firstFrame, text = "Please select a save directory and also directories\
for flats, biases, and darks to create masters of each")
self.flatsLabel = tk.Label(self.firstFrame, text = "Please enter flats directory: ")
self.flatsText = tk.StringVar(value = "")
self.flatsEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.flatsText)
self.browseflats = tk.Button(self.firstFrame, text = "Browse",
command = lambda: self.uploadFlats(self.flatsText))
self.flatsLabel = tk.Label(self.firstFrame, text = "Please enter flats directory: ")
self.flatsText = tk.StringVar()
self.flatsEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.flatsText)
self.browseflats = tk.Button(self.firstFrame, text = "Browse", command = self.uploadFlats)
self.darksLabel = tk.Label(self.firstFrame, text = "Please enter darks directory: ")
self.darksText = tk.StringVar()
self.darksEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.darksText)
self.browsedarks = tk.Button(self.firstFrame, text = "Browse", command = self.uploadDarks)
self.biasLabel = tk.Label(self.firstFrame, text = "Please enter bias directory: ")
self.biasText = tk.StringVar()
self.biasEntry = tk.Entry(self.firstFrame, width = 50, textvariable = self.biasText)
self.browsebias = tk.Button(self.firstFrame, text = "Browse", command = self.uploadBias)
self.enterButton = tk.Button(self.firstFrame, text = "Create Masters", command = self.mastercalibrations)
#-----------------------------------------------------------------------------------------------------------------------
# Placement
self.firstFrame.pack()
self.secondFrame.pack(side = 'left', padx = 5, pady = 5)
self.thirdFrame.pack(side = 'right', padx = 5, pady = 5)
#First Frame
self.initialY = 5
self.spacing = 30
self.description.place(x = 5, y = 5)
self.flatsLabel.place(x = 5, y = self.initialY + self.spacing)
self.flatsEntry.place(x = 200, y = self.initialY + self.spacing)
self.browseflats.place(x = 510, y = self.initialY + self.spacing)
self.darksLabel.place(x = 5, y = self.initialY + 2 * self.spacing)
self.darksEntry.place(x = 200, y = self.initialY + 2 * self.spacing)
self.browsedarks.place(x = 510, y = self.initialY + 2 * self.spacing)
self.biasLabel.place(x = 5, y = self.initialY + 3 * self.spacing)
self.biasEntry.place(x = 200, y = self.initialY + 3 * self.spacing)
self.browsebias.place(x = 510, y = self.initialY + 3 * self.spacing)
self.enterButton.place(x = 5, y = self.initialY + 4 * self.spacing)
self.mainWin.mainloop()
#-----------------------------------------------------------------------------------------------------------------------
def uploadFlats(self, entry):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
entry.set(0, self.directory)
def uploadDarks(self):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
self.darksEntry.delete(0, 'end')
self.darksEntry.insert(0, self.directory)
def uploadBias(self):
self.directory = dlg.askdirectory()
#Delete current text in image name entry and replace with found image name
self.biasEntry.delete(0, 'end')
self.biasEntry.insert(0, self.directory)
def mastercalibrations(self):
print('m')
I have tried using lambda functions, the partial function, and have tried seeing if it is just an issue with the my function itself. Regardless of what the uploadFlats actually does, I'm given this same error. I have tried sending in multiple different types of variables, however they are all consistently ignored.

How to save a tkinter canvas as an image

I would like to save my drawing on a tkinter canvas as an image so I can open it for later use. I currently use this save system from this post however this is not a good way for me. First I would need to add an offset and second if i set the application so only some part of the canvas is actually visible, the part where the canvas is not visible appears black when saving the image.
only part of the canvas is actually visible. If I open the saved image this is what it looks like only what was visible is actually there(the entire image was yellow before saving it).
The code of saving the image.
def save(widget(canvas), filelocation):
x=root.winfo_rootx()+widget.winfo_x() + 74
y=root.winfo_rooty()+widget.winfo_y() + 109
x1=x+widget.winfo_width()
y1=y+widget.winfo_height()
ImageGrab.grab().crop((x,y,x1,y1)).save(filelocation)
Idea
After reading from this post it explains i could recreate all the stuff i drew on the canvas. So my idea is to put all the stuff i drew on the canvas such as lines i created on an invisible layer and paste it on the image. However i dont know if this is possible(may be possible with PIL, numpy or cv2)
Code(Is minimal reproducable)
import tkinter as tk
from tkinter import colorchooser, Canvas, N
from tkinter.ttk import *
from PIL import Image, ImageTk, ImageGrab
import keyboard
def save(widget, filelocation):
x=root.winfo_rootx()+widget.winfo_x()
y=root.winfo_rooty()+widget.winfo_y()
x1=x+widget.winfo_width()
y1=y+widget.winfo_height()
ImageGrab.grab().crop((x,y,x1,y1)).save(filelocation)
def type_of(color):
type_pen = 'marker'
if type_pen == 'marker':
pencil_motion_marker(color = color)
#pixel pen
def pencil_motion_marker(color):
stage.bind('<Button-1>', get_pos_marker)
stage.bind('<B1-Motion>', lambda event, color = color: pencil_draw_marker(event, color))
def get_pos_marker(event):
global lastx, lasty
lastx, lasty = event.x, event.y
def pencil_draw_marker(event, color):
stage.create_line((lastx, lasty, event.x, event.y), width = width.get(), fill = color, capstyle = 'round')
get_pos_marker(event)
def choose_pen_color():
pencilcolor = colorchooser.askcolor(title = 'Pencil Color')
type_of(pencilcolor[1])
##
def pencil_click():
global width, opacity
Whitepencolb = Button(optionsframe, text = 'Whitepencolimg', style = 'COLBG.TButton', command = lambda m = 'White': type_of(m))
Whitepencolb.grid(row = 0, column = 0, padx = 10, pady = 1)
Redpencolb = Button(optionsframe, text = 'Redpencolimg', style = 'COLBG.TButton', command = lambda m = 'Red': type_of(m))
Redpencolb.grid(row = 1, column = 0, padx = 10, pady = 1)
Magentapencolb = Button(optionsframe, text = 'Magentapencolimg', style = 'COLBG.TButton', command = lambda m = 'Magenta': type_of(m))
Magentapencolb.grid(row = 0, column = 1, padx = 10, pady = 1)
Limegreenpencolb = Button(optionsframe, text = 'Limegreenpencolimg', style = 'COLBG.TButton', command = lambda m = 'Lime': type_of(m))
Limegreenpencolb.grid(row = 1, column = 1, padx = 10, pady = 1)
Greenpencolb = Button(optionsframe, text = 'Greenpencolimg', style = 'COLBG.TButton', command = lambda m = 'Green': type_of(m))
Greenpencolb.grid(row = 0, column = 2, padx = 10, pady = 1)
Bluepencolb = Button(optionsframe, text = 'Bluepencolimg', style = 'COLBG.TButton', command = lambda m = 'Blue': type_of(m))
Bluepencolb.grid(row = 1, column = 2, padx = 10, pady = 1)
Cyanpencolb = Button(optionsframe, text = 'Cyanpencolimg', style = 'COLBG.TButton', command = lambda m = 'Cyan': type_of(m))
Cyanpencolb.grid(row = 0, column = 3, padx = 10, pady = 1)
Yellowpencolb = Button(optionsframe, text = 'Yellowpencolimg', style = 'COLBG.TButton', command = lambda m = 'Yellow': type_of(m))
Yellowpencolb.grid(row = 1, column = 3, padx = 10, pady = 1)
Orangepencolb = Button(optionsframe, text = 'Orangepencolimg', style = 'COLBG.TButton', command = lambda m = 'Orange': type_of(m))
Orangepencolb.grid(row = 0, column = 4, padx = 10, pady = 1)
Graypencolb = Button(optionsframe, text = 'Graypencolimg', style = 'COLBG.TButton', command = lambda m = 'Gray': type_of(m))
Graypencolb.grid(row = 1, column = 4, padx = 10, pady = 1)
Blackpencolb = Button(optionsframe, text = 'Blackpencolimg', style = 'COLBG.TButton', command = lambda m = 'Black': type_of(m))
Blackpencolb.grid(row = 0, column = 5, padx = 10, pady = 1)
Createnewpencolb = Button(optionsframe, text = 'Createnewpencolimg', style = 'COLBG.TButton', command = choose_pen_color)
Createnewpencolb.grid(row = 1, column = 5, padx = 10, pady = 1)
widthlabel = Label(optionsframe, text = 'Width: ', style = 'LABELBG.TLabel')
width = Scale(optionsframe, from_ = 1, to = 20, style = 'SCALEBG.Horizontal.TScale')
widthlabel.grid(row = 0, column = 6)
width.grid(row = 0, column = 7)
width.set(20)
opacitylabel = Label(optionsframe, text = 'Opacity: ', style = 'LABELBG.TLabel')
opacity = Scale(optionsframe, from_ = 0, to = 1.0, style = 'SCALEBG.Horizontal.TScale')
opacitylabel.grid(row = 1, column = 6)
opacity.grid(row = 1, column = 7)
opacity.set(1.0)
def setup(filelocation):
global stage, img_id, optionsframe, draw
for widgets in root.winfo_children():
widgets.destroy()
root.config(bg = '#454545')
iconsframewidth = int(screen_width / 20)
frames = Style()
frames.configure('FRAMES.TFrame', background = '#2a2a2a')
sep = Style()
sep.configure('SEP.TFrame', background = '#1a1a1a')
style = Style()
style.configure('STAGE.TFrame', background = '#454545')
icon = Style()
icon.configure('ICON.TButton', background = '#2a2a2a', foreground = '#2a2a2a')
iconsframe = Frame(root, width = iconsframewidth, style = 'FRAMES.TFrame')
iconsframe.pack(side = 'left', expand = False, fill = 'y')
iconsframe.pack_propagate(0)
sep1frame = Frame(root, style = 'SEP.TFrame', width = 5)
sep1frame.pack(side = 'left', expand = False, fill = 'y')
optionsframe = Frame(root, style = 'FRAMES.TFrame', height = 100)
optionsframe.pack(side = 'top', expand = False, fill = 'x')
optionsframe.pack_propagate(0)
sep2frame = Frame(root, style = 'SEP.TFrame', height = 5)
sep2frame.pack(side = 'top', expand = False, fill = 'x')
propertyframe = Frame(root, style = 'FRAMES.TFrame', width = 150)
propertyframe.pack(side = 'right', expand = False, fill = 'y')
propertyframe.pack_propagate(0)
sep3frame = Frame(root, style = 'SEP.TFrame', width = 5)
sep3frame.pack(side = 'right', expand = False, fill = 'y')
stageframe = Frame(root, style = 'STAGE.TFrame')
stageframe.pack(side = 'top', expand = True, fill = 'both')
stageframe.pack_propagate(0)
image = Image.open(filelocation)
width, height = image.size
stage = Canvas(stageframe, width = width, height = height)
stage.pack(side="top", anchor = 'c', expand=True)
root.update()
keyboard.add_hotkey("ctrl+s", lambda widget = stage, filelocation = filelocation: save(widget, filelocation))
pencilbutton = Button(iconsframe, text = 'pencilimg', command = pencil_click, style = 'ICON.TButton')
pencilbutton.pack(anchor = N, pady = 10)
imgtk = ImageTk.PhotoImage(Image.open(filelocation))
img_id = stage.create_image(stage.winfo_width() / 2, stage.winfo_height() / 2, image = imgtk)
stage.image = imgtk
root = tk.Tk()
root.title('App')
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
w = 1150
h = 600
x = (screen_width / 2) - (w / 2)
y = (screen_height / 2) - (h / 2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.minsize(1150, 600)
setup('Test.png')
root.mainloop()
Image
Small Problem
Replying to #Claudio : I am using the screenshot technique for saving Canvas as an image to a file right now. I noticed that the saved canvas image looks like this at the corner and after saving and reopening the image it looks like this ( the border of the canvas increases the size of the canvas image ).
Update 2. June 2022: Small Problem Solved by the updated code provided in the accepted answer.
How to save a tkinter Canvas graphics as an image?
It seems to be a fact that tkinter doesn't provide a direct method
allowing to get an image of Canvas graphics for saving it to an image
file. There are two ways around this problem requiring solely an import
of the Python PIL module (Pillow).
One of this ways is to perform a screenshot of painting on the
Canvas area which can be done using PIL.ImageGrab.grab() or any other
of the various methods for performing (cropped) screenshots and saving
them to an image file
( see e.g. Fast screenshot of a small part of the screen in Python
for a Python screenshot module fast enough to allow to make a video of
the progressing painting on the Canvas ).
Another way is to paint on a Python PIL image updating the tkinter Canvas
with the modified PIL image saving it then to a file using the .save()
method available for saving PIL image objects.
The code provided in the question works generally as expected if save()
uses both the Frame (stageframe) and the Canvas (stage) widgets
required for getting the right x,y values for cropping of the screenshot
in case the Canvas is placed within a Frame AND if the bounding box for cropping
the screenshot takes into account that tkinter Canvas widget size
includes a Canvas border and a Canvas highlight-border.
The code below is the in the question provided code with some added
comments and appropriate modifications. It doesn't require the keyboard
module and saves the by painting modified Canvas as image file by
clicking on the most-left upper pencilbutton handled by the
pencil_click() function.
It provides both methods for saving the graphics of the tkinter Canvas
to an image file. Select one of them by assigning appropriate value to
the global method variable ( method = 'screenshot' or
method = 'imagepaint' ):
# https://stackoverflow.com/questions/72459847/how-to-save-a-tkinter-canvas-as-an-image
from tkinter import Tk, colorchooser, Canvas, N, PhotoImage
from tkinter.ttk import Style, Frame, Button, Label, Scale
from PIL import Image, ImageTk # required to load images in tkinter
# method = 'screenshot' or 'imagepaint'
method = 'screenshot'
borderthickness_bd = 2
highlightthickness = 1
if method == 'imagepaint':
from PIL import ImageDraw # required to draw on the image
if method == 'screenshot':
from PIL import ImageGrab # required for the screenshot
filelocation = 'Test.png'
savelocation = 'Test_.png'
def save(stageframe, stage, savelocation):
if method == 'imagepaint':
global image
image.save(savelocation)
if method == 'screenshot':
global borderthickness_bd, highlightthickness
brdt = borderthickness_bd + highlightthickness
# +1 and -2 because of thicknesses of Canvas borders (bd-border and highlight-border):
x=root.winfo_rootx()+stageframe.winfo_x()+stage.winfo_x() +1*brdt
y=root.winfo_rooty()+stageframe.winfo_y()+stage.winfo_y() +1*brdt
x1=x+stage.winfo_width() -2*brdt
y1=y+stage.winfo_height()-2*brdt
ImageGrab.grab().crop((x,y,x1,y1)).save(savelocation)
def type_of(color):
type_pen = 'marker'
if type_pen == 'marker':
pencil_motion_marker(color = color)
#pixel pen
def pencil_motion_marker(color):
stage.bind('<Button-1>' , get_pos_marker)
stage.bind('<B1-Motion>', lambda event, color = color: pencil_draw_marker(event, color))
def get_pos_marker(event):
global lastx, lasty
lastx, lasty = event.x, event.y
def pencil_draw_marker(event, color):
global method, lastx, lasty, draw, image, img_id
# print( (lastx, lasty, event.x, event.y), color, int(width.get()) )
if method == 'screenshot':
stage.create_line((lastx, lasty, event.x, event.y), width = width.get(), fill = color, capstyle = 'round')
get_pos_marker(event)
if method == 'imagepaint':
w12 = int(width.get()/2)
draw.ellipse( (event.x-w12, event.y-w12, event.x+w12, event.y+w12), fill=color )
imgtk = ImageTk.PhotoImage(image)
stage.itemconfig(img_id, image=imgtk)
stage.image = imgtk
def choose_pen_color():
pencilcolor = colorchooser.askcolor(title = 'Pencil Color')
type_of(pencilcolor[1])
##
def pencil_click():
global width, opacity, stageframe, stage, savelocation
# imgToSave = stage.image # gives a PhotoImage object
# imgToSave._PhotoImage__photo.write("Test.gif", format='gif') # which can be saved, but ...
# ^--- ... with no painting done on Canvas - only the image.
save(stageframe, stage, savelocation)
Whitepencolb = Button(optionsframe, text = 'Whitepencolimg', style = 'COLBG.TButton', command = lambda m = 'White': type_of(m))
Whitepencolb.grid(row = 0, column = 0, padx = 10, pady = 1)
Redpencolb = Button(optionsframe, text = 'Redpencolimg', style = 'COLBG.TButton', command = lambda m = 'Red': type_of(m))
Redpencolb.grid(row = 1, column = 0, padx = 10, pady = 1)
Magentapencolb = Button(optionsframe, text = 'Magentapencolimg', style = 'COLBG.TButton', command = lambda m = 'Magenta': type_of(m))
Magentapencolb.grid(row = 0, column = 1, padx = 10, pady = 1)
Limegreenpencolb = Button(optionsframe, text = 'Limegreenpencolimg', style = 'COLBG.TButton', command = lambda m = 'Lime': type_of(m))
Limegreenpencolb.grid(row = 1, column = 1, padx = 10, pady = 1)
Greenpencolb = Button(optionsframe, text = 'Greenpencolimg', style = 'COLBG.TButton', command = lambda m = 'Green': type_of(m))
Greenpencolb.grid(row = 0, column = 2, padx = 10, pady = 1)
Bluepencolb = Button(optionsframe, text = 'Bluepencolimg', style = 'COLBG.TButton', command = lambda m = 'Blue': type_of(m))
Bluepencolb.grid(row = 1, column = 2, padx = 10, pady = 1)
Cyanpencolb = Button(optionsframe, text = 'Cyanpencolimg', style = 'COLBG.TButton', command = lambda m = 'Cyan': type_of(m))
Cyanpencolb.grid(row = 0, column = 3, padx = 10, pady = 1)
Yellowpencolb = Button(optionsframe, text = 'Yellowpencolimg', style = 'COLBG.TButton', command = lambda m = 'Yellow': type_of(m))
Yellowpencolb.grid(row = 1, column = 3, padx = 10, pady = 1)
Orangepencolb = Button(optionsframe, text = 'Orangepencolimg', style = 'COLBG.TButton', command = lambda m = 'Orange': type_of(m))
Orangepencolb.grid(row = 0, column = 4, padx = 10, pady = 1)
Graypencolb = Button(optionsframe, text = 'Graypencolimg', style = 'COLBG.TButton', command = lambda m = 'Gray': type_of(m))
Graypencolb.grid(row = 1, column = 4, padx = 10, pady = 1)
Blackpencolb = Button(optionsframe, text = 'Blackpencolimg', style = 'COLBG.TButton', command = lambda m = 'Black': type_of(m))
Blackpencolb.grid(row = 0, column = 5, padx = 10, pady = 1)
Createnewpencolb = Button(optionsframe, text = 'Createnewpencolimg', style = 'COLBG.TButton', command = choose_pen_color)
Createnewpencolb.grid(row = 1, column = 5, padx = 10, pady = 1)
widthlabel = Label(optionsframe, text = 'Width: ', style = 'LABELBG.TLabel')
width = Scale(optionsframe, from_ = 1, to = 100, style = 'SCALEBG.Horizontal.TScale')
widthlabel.grid(row = 0, column = 6)
width.grid(row = 0, column = 7)
width.set(20)
opacitylabel = Label(optionsframe, text = 'Opacity: ', style = 'LABELBG.TLabel')
opacity = Scale(optionsframe, from_ = 0, to = 1.0, style = 'SCALEBG.Horizontal.TScale')
opacitylabel.grid(row = 1, column = 6)
opacity.grid(row = 1, column = 7)
opacity.set(1.0)
def setup(filelocation):
global stage, stageframe, img_id, optionsframe, draw, image, img_id, method
global borderthickness_bd, highlightthickness
for widgets in root.winfo_children():
widgets.destroy()
root.config(bg = '#454545')
iconsframewidth = int(screen_width / 20)
frames = Style()
frames.configure('FRAMES.TFrame', background = '#2a2a2a')
sep = Style()
sep.configure('SEP.TFrame', background = '#1a1a1a')
style = Style()
style.configure('STAGE.TFrame', background = '#454545')
icon = Style()
icon.configure('ICON.TButton', background = '#2a2a2a', foreground = '#2a2a2a')
iconsframe = Frame(root, width = iconsframewidth, style = 'FRAMES.TFrame')
iconsframe.pack(side = 'left', expand = False, fill = 'y')
iconsframe.pack_propagate(0)
sep1frame = Frame(root, style = 'SEP.TFrame', width = 5)
sep1frame.pack(side = 'left', expand = False, fill = 'y')
optionsframe = Frame(root, style = 'FRAMES.TFrame', height = 100)
optionsframe.pack(side = 'top', expand = False, fill = 'x')
optionsframe.pack_propagate(0)
sep2frame = Frame(root, style = 'SEP.TFrame', height = 5)
sep2frame.pack(side = 'top', expand = False, fill = 'x')
propertyframe = Frame(root, style = 'FRAMES.TFrame', width = 150)
propertyframe.pack(side = 'right', expand = False, fill = 'y')
propertyframe.pack_propagate(0)
sep3frame = Frame(root, style = 'SEP.TFrame', width = 5)
sep3frame.pack(side = 'right', expand = False, fill = 'y')
stageframe = Frame(root, style = 'STAGE.TFrame')
stageframe.pack(side = 'top', expand = True, fill = 'both')
stageframe.pack_propagate(0)
image = Image.open(filelocation)
width, height = image.size
if method == 'imagepaint':
draw = ImageDraw.Draw(image)
imgtk = ImageTk.PhotoImage(image)
# width, height = imgtk._PhotoImage__size
# imgtk = PhotoImage(filelocation)
# ^--- no width, hight information ???
stage = Canvas(stageframe, width = width, height = height, bd=borderthickness_bd, highlightthickness=highlightthickness) # default: bd=2, highlightthickness=1
stage.pack(side="top", anchor = 'c', expand=True)
root.update()
# keyboard.add_hotkey("ctrl+s", lambda widget = stageframe, filelocation = filelocation: save(widget, filelocation))
pencilbutton = Button(iconsframe, text = 'pencilimg', command = pencil_click, style = 'ICON.TButton')
pencilbutton.pack(anchor = N, pady = 10)
img_id = stage.create_image(stage.winfo_width() / 2, stage.winfo_height() / 2, image = imgtk)
stage.image = imgtk
root = Tk()
root.title('App')
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
w = 1150
h = 600
x = (screen_width / 2) - (w / 2)
y = (screen_height / 2) - (h / 2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.minsize(1150, 600)
setup(filelocation)
root.mainloop()
Cropping a screenshot as a way of saving the graphics of tkinter Canvas
is to be preferred over painting on a PIL image updating the tkinter
Canvas because the latter has the side effect of slowing graphics
down so painting smoothness suffer.
To see how to change the look of a button in tkinter (to change
after the first click the pencilbutton to a savebutton), check out
Python tkinter: error _tkinter.TclError: bad window path name ".!button2" for how it can be done.

Traceback (most recent call last): AttributeError: 'NoneType' object has no attribute 'place' [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 11 months ago.
enter image description here
hi
I have an error in my python code can you guys help me to solve it
thee error:
Traceback (most recent call last):
File "C:\Users\yasen\Desktop\برمجة\graphics\main11.py", line 69, in <module>
firstname_text.place(x = 540, y = 70)
AttributeError: 'NoneType' object has no attribute 'place
my code
from tkinter import *
import pandas as pd
def send_info():
path = 'Registers.form.xlsx'
df1 = pd.read_excel(path)
SeriesA = df1['firstname']
SeriesB = df1['secondname']
SeriesC = df1['thirdname']
SeriesD = df1['age']
SeriesE = df1['phonenumber']
SeriesF = df1['Departmentname']
SeriesG = df1['familymembers']
SeriesH = df1['bookingdate']
A = pd.Series(firstname.get)
B = pd.Series(secondname.get)
C = pd.Series(thirdname.get)
D = pd.Series(age.get)
E = pd.Series(phonenumber.get)
F = pd.Series(Departmentname.get)
G = pd.Series(familymembers.get)
H = pd.Series(bookingdate.get)
SeriesA = SeriesA.append(A)
SeriesB = SeriesA.append(B)
SeriesC = SeriesA.append(C)
SeriesD = SeriesA.append(D)
SeriesE = SeriesA.append(E)
SeriesF = SeriesA.append(F)
SeriesG = SeriesA.append(G)
SeriesH = SeriesA.append(H)
df2 = pd.DataFrame({"firstname": SeriesA, "secondnamer": SeriesB, "thirdname": SeriesC, "age": SeriesD, "phonenumber": SeriesE, "Departmentname": SeriesF, "familymembers": SeriesG, "bookingdate": SeriesH})
df2.to_excel(path, index=False)
firstname_entry.delete(0, END)
secondname_entry.delete(0, END)
thirdname_entry.delete(0, END)
age_entry.delete(0, END)
phonenumber_entry.delete(0, END)
Departmentname_entry.delete(0, END)
familymembers_entry.delete(0, END)
bookingdate_entry.delete(0, END)
screen = Tk()
screen.geometry("1080x1080")
screen.title("مديرية شؤون البطاقة الوطنية")
welcome_text = Label(text="أهلا وسهلا بكم في الحجز الالكتروني للبطاقة الموحدة ", fg="white", bg="green",height=2 ,width=1080)
welcome_text.grid()
firstname_text = Label(text = "الاسم الاول * ",).grid(row=0)
secondname_text = Label(text = "الاسم الثاني * ",).grid(row=1)
thirdname_text = Label(text = "الاسم الثالث * ",).grid(row=2)
age_text = Label(text = "العمر * ",).grid(row=3)
phonenumber_text = Label(text = "رقم الهاتف * ",).grid(row=4)
Departmentname_text = Label(text = "اسم دائرة الاحوال المدنية * ",).grid(row=5)
familymembers_text = Label(text = "عدد افراد الاسرة * ",).grid(row=6)
bookingdate_text = Label(text = "موعد تاريخ الحجز المطلوب * ",).grid(row=7)
firstname_text.place(x = 540, y = 70)
secondname_text.place(x = 540, y = 130)
thirdname_text.place(x = 540, y = 190)
age_text.place(x = 540, y = 250)
phonenumber_text.place(x = 540, y = 310)
Departmentname_text.place(x = 540, y = 370)
familymembers_text.place(x = 540, y = 430)
bookingdate_text.place(x = 540, y = 490)
firstname = StringVar()
secondname = StringVar()
thirdname = StringVar()
age = StringVar()
phonenumber = StringVar()
Departmentname = StringVar()
familymembers = StringVar()
bookingdate = StringVar()
firstname_entry = Entry(textvariable = firstname, width = "40")
secondname_entry = Entry(textvariable = secondname, width = "40")
thirdname_entry = Entry(textvariable = thirdname, width = "40")
age_entry = Entry(textvariable = age, width = "40")
phonenumber_entry = Entry(textvariable = phonenumber, width = "40")
Departmentname_entry = Entry(textvariable = Departmentname, width = "40")
familymembers_entry = Entry(textvariable = familymembers, width = "40")
bookingdate_entry = Entry(textvariable = bookingdate, width = "40")
firstname_entry.place(x = 450, y = 100)
secondname_entry.place(x = 450, y = 160)
thirdname_entry.place(x = 450, y = 220)
age_entry.place(x = 450, y = 280)
phonenumber_entry.place(x = 450, y = 340)
Departmentname_entry.place(x = 450, y = 400)
familymembers_entry.place(x = 450, y = 460)
bookingdate_entry.place(x = 450, y = 520)
firstname_entry.grid(row=0,column=1)
secondname_entry.grid(row=1,column=1)
thirdname_entry.grid(row=2,column=1)
age_entry.grid(row=3,column=1)
phonenumber_entry.grid(row=4,column=1)
Departmentname_entry.grid(row=5,column=1)
familymembers_entry.grid(row=6,column=1)
bookingdate_entry.grid(row=7,column=1)
register = Button(screen,text = "Register", width = "60", height = "2", command = send_info, bg = "grey").grid(row=3,column=1, pady=4)
register.place(x = 360, y = 600)
screen.mainloop ()
The first argument passed into the Label() constructor should be your root, so your label should be initialized like so:
firstname_text = Label(screen, text = "الاسم الاول * ",).grid(row=0)
And you just do the same thing for all the labels you initialized, you should then be able to use the place method since there's now a root with coordinates to place it on.

Open a new frame so it changes and displays a new page

I am trying to create a login page, when the user clicks the login button it is supposed to display a new page (not Toplevel, and create a new window), but it doesn't seem to work.
root = Tk()
root.geometry('670x466')
accounts = []
class Goode_brothers:
def __init__(self, parent):
self.myFrame = Frame(parent)
self.myFrame.pack()
self.load = Image.open('new-dip-project\\food.jpg')
self.render = ImageTk.PhotoImage(self.load)
self.img = Label(parent, image = self.render)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.b1 = Button(parent,image = self.img_login, command = self.read_info, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b1.place(x = 275, y = 340)
self.img_register = PhotoImage(file = 'new-dip-project\\register.png')
self.b2 = Button(parent,image = self.img_register, command = self.openNewWindow, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b2.place(x = 265, y = 400)
self.canvas = Canvas(parent, width = 400, height = 120)
self.canvas.pack()
self.img4 = ImageTk.PhotoImage(Image.open('new-dip-project\\goode.png'))
self.canvas.create_image(20, 20, anchor=NW, image=self.img4)
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
self.password = Entry(parent)
self.password.place(x = 354, y = 250)
self.img_label = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(parent, image = self.img_label, text = "Email:", bg = '#3c3a3b').place(x = 197,y = 178)
self.img_label_pass = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(parent, image = self.img_label_pass, text = "Password:", bg = '#3c3a3b').place(x = 177,y = 245)
def openMenu(self):
self.myFrame.destroy
self.myFrame2 = Frame()
self.myFrame2.pack()
def read_info(self):
with open("emails.txt") as read_ep:
for line in read_ep:
accounts.append(line.strip().split(", "))
credential = [self.email.get(), self.password.get()]
if credential in accounts:
self.openMenu()
else:
self.ep_notexist = Label(root, text = "Your Email or Password is incorrect, Please try again", font=("open sans", "8"))
self.ep_notexist.place(x = 210, y = 300)
self.ep_notexist.after(4000, self.ep_notexist.destroy)
First destroy all the widgets placed of login page by using
for wid in root.winfo_children():
wid.destroy()
and then pack your new frame. It will work.
(if you don't want to destroy widgets you can also use wid.pack_forget() if you have used pack to place widgets)
You actually do not destroy the frame in the below line:
def openMenu(self):
self.myFrame.destroy # <--- frame is not destroyed actually
It should be:
def openMenu(self):
self.myFrame.destroy()

how to solve AttributeError in python and tkinter?

I want to display the values in the text boxes, but i'm getting this error:
blue.set(B_mean1)
AttributeError: 'numpy.ndarray' object has no attribute 'set'
and my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections import *
from CBIR import *
from experiment import *
from scipy.spatial import distance
import Tkinter,tkFileDialog
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent,background="light grey")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
custName.set(path)
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 100, y = 100)
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
dis_list1 = list()
imge = cv2.imread(path)
arr = array(imge)
g_img = cv2.imread(path,0)
gray_re_img = cv2.resize(g_img,(256,256))
graylist1.append(gray_re_img)
equ = cv2.equalizeHist(gray_re_img)
eq_graylist1.append(equ)
re_img = cv2.resize(imge,(256,256))
resizelist1.append(re_img)
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
im = skimage.io.imread(path, as_grey=True)
im = skimage.img_as_ubyte(im)
im /= 32
g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
cont_list1.append(cont)
ene = skimage.feature.greycoprops(g, 'energy')[0][0]
ene_list1.append(ene)
homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
homo_list1.append(homo)
cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
cor_list1.append(cor)
dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
dis_list1.append(dis)
feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
blue.set(B_mean1)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
label = Label(app, text='Python Image Search', fg = 'black',font = 'PoorRichard 24')
label.pack()
label.place(y = 5, x = 0)
img = Image.open('logo.png')
bg_img = ImageTk.PhotoImage(img)
label1 = Label(app, image = bg_img)
label1.place(y = 5, x = 1225)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.grid(column=0,row=0,sticky='EW')
yourName.update()
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 60, x = 100, width = 525, height = 25)
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar()
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
All I want to know is how to display the values into the textbox. Any suggestions are welcome.
Thanks in advance!
Your problem is that you are using the variable name blue for two different things. At one point it's a numpy array and at another it is an IntVar. When you call blue.set(...), you are doing that at the point where blue references a numpy array, hence the error message 'numpy.ndarray' object has no attribute 'set'
Try changing the name of your IntVar to something else, such as blue_var, and make sure you change it everywhere.

Categories

Resources